package com.richapp.launcher.net.mobile.server;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jack.netty.tcp.server.TLVServer;
import com.jack.netty.tcp.server.TLVServerListener;
import com.jack.util.date.DateUtil;
import com.jack.util.hex.HexUtil;
import com.jack.util.string.StringUtil;
import com.richapp.launcher.busevent.EventPhoneAction;
import com.richapp.launcher.busevent.EventUnbindBox;
import com.richapp.launcher.control.MoveControl;
import com.richapp.launcher.control.PageControl;
import com.richapp.launcher.control.PhoneControl;
import com.richapp.launcher.control.VolumeControl;
import com.richapp.launcher.database.infrared.dao.BrandDao;
import com.richapp.launcher.database.infrared.dao.BrandModelButtonDao;
import com.richapp.launcher.database.infrared.dao.BrandModelDao;
import com.richapp.launcher.database.infrared.dao.ButtonDao;
import com.richapp.launcher.database.infrared.dao.MachineTypeDao;
import com.richapp.launcher.database.infrared.mode.Brand;
import com.richapp.launcher.database.infrared.mode.BrandModel;
import com.richapp.launcher.database.infrared.mode.BrandModelButton;
import com.richapp.launcher.database.infrared.mode.Button;
import com.richapp.launcher.database.infrared.mode.MachineType;
import com.richapp.launcher.database.system.dao.ActionInfraredModelDao;
import com.richapp.launcher.database.system.dao.ActionModelDao;
import com.richapp.launcher.database.system.dao.BoxLoginDao;
import com.richapp.launcher.database.system.dao.BoxModelDao;
import com.richapp.launcher.database.system.dao.BoxPhoneDao;
import com.richapp.launcher.database.system.dao.ConditionSensorModelDao;
import com.richapp.launcher.database.system.dao.ConditionStatusModelDao;
import com.richapp.launcher.database.system.dao.ConditionTimeModelDao;
import com.richapp.launcher.database.system.dao.DeviceDayPowerConsumptionDao;
import com.richapp.launcher.database.system.dao.DeviceModelDao;
import com.richapp.launcher.database.system.dao.DeviceModelHistoryDao;
import com.richapp.launcher.database.system.dao.DeviceMonthPowerConsumptionDao;
import com.richapp.launcher.database.system.dao.RoomModelDao;
import com.richapp.launcher.database.system.dao.SceneActionDao;
import com.richapp.launcher.database.system.dao.SceneModelDao;
import com.richapp.launcher.database.system.dao.SystemValueModelDao;
import com.richapp.launcher.database.system.dao.UserLoginDao;
import com.richapp.launcher.database.system.dao.UserMachineButtonDao;
import com.richapp.launcher.database.system.dao.UserMachineDao;
import com.richapp.launcher.database.system.dao.UserModelDao;
import com.richapp.launcher.database.system.mode.ActionInfraredModel;
import com.richapp.launcher.database.system.mode.ActionModel;
import com.richapp.launcher.database.system.mode.BoxLogin;
import com.richapp.launcher.database.system.mode.BoxModel;
import com.richapp.launcher.database.system.mode.BoxPhone;
import com.richapp.launcher.database.system.mode.ConditionSensorModel;
import com.richapp.launcher.database.system.mode.ConditionStatusModel;
import com.richapp.launcher.database.system.mode.ConditionTimeModel;
import com.richapp.launcher.database.system.mode.DeviceModel;
import com.richapp.launcher.database.system.mode.RoomModel;
import com.richapp.launcher.database.system.mode.SceneActionModel;
import com.richapp.launcher.database.system.mode.SceneModel;
import com.richapp.launcher.database.system.mode.SystemValueModel;
import com.richapp.launcher.database.system.mode.UserLogin;
import com.richapp.launcher.database.system.mode.UserMachine;
import com.richapp.launcher.database.system.mode.UserMachineButton;
import com.richapp.launcher.database.system.mode.UserModel;
import com.richapp.launcher.net.MessageIdManager;
import com.richapp.launcher.net.box.tcp.client.BoxClient;
import com.richapp.launcher.net.box.tcp.client.BoxClientManager;
import com.richapp.launcher.net.box.tcp.server.BoxServer;
import com.richapp.launcher.net.message.MsgConstant;
import com.richapp.launcher.net.mobile.message.DevicePowerConsumptionReply;
import com.richapp.launcher.net.mobile.message.DeviceStatusReply;
import com.richapp.launcher.net.mobile.message.InfoReply;
import com.richapp.launcher.net.mobile.message.SceneInfoReply;
import com.richapp.launcher.net.mobile.message.UserInfoReply;
import com.richapp.launcher.net.mobile.message.UserLogoutReply;
import com.richapp.launcher.net.remote.RemoteClient;
import com.richapp.launcher.receiver.LauncherMessageReceiver;
import com.richapp.launcher.scene.SceneServer;
import com.richapp.launcher.serialport.gateway.GatewaytConstant;
import com.richapp.launcher.serialport.gateway.command.AddCmd;
import com.richapp.launcher.serialport.gateway.command.ControlDeviceCmd;
import com.richapp.launcher.serialport.gateway.command.InfraredControlCmd;
import com.richapp.launcher.serialport.gateway.command.InfraredStudyCmd;
import com.richapp.launcher.serialport.gateway.command.QueryCmd;
import com.richapp.launcher.serialport.gateway.command.RestCmd;
import com.richapp.launcher.serialport.infrared.InfraredServer;
import com.richapp.launcher.serialport.infrared.message.ControlMessage;
import com.richapp.launcher.serialport.infrared.message.StudyMessage;
import com.richapp.launcher.utils.Constants;
import com.richapp.launcher.utils.JackMd5;
import com.richapp.launcher.utils.Tools;
import com.richapp.net.util.HexTool;
import com.tasogo.RemoteLib.Remote_obj;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import de.greenrobot.event.EventBus;
import hdp.http.HdpKit;

/**
 * Created by jack on 2015/5/4 0004.
 */
public class UserServer extends TLVServer implements TLVServerListener {
    private  static  final String TAG = UserServer.class.getName();

    private static UserServer userServer;
    private Context context;
    private DeviceModel dmList2=null;
    private BoxModelDao boxModelDao = null;
    private BoxPhoneDao boxPhoneDao = null;
    private UserModelDao userModelDao = null;
    private RoomModelDao roomModelDao = null;
    private DeviceModelDao deviceModelDao = null;
    private DeviceModelHistoryDao deviceModelHistoryDao = null;
    private DeviceDayPowerConsumptionDao deviceDayPowerConsumptionDao;
    private DeviceMonthPowerConsumptionDao deviceMonthPowerConsumptionDao;

    private SystemValueModelDao systemValueModelDao = null;
    private SceneModelDao sceneModelDao = null;
    private ConditionSensorModelDao conditionSensorModelDao;
    private ConditionStatusModelDao conditionStatusModelDao;
    private ConditionTimeModelDao conditionTimeModelDao;
    private ActionModelDao actionModelDao;
    private ActionInfraredModelDao actionInfraredModelDao;
    private MachineTypeDao machineTypeDao;
    private BrandDao brandDao;
    private ButtonDao buttonDao;
    private BrandModelDao brandModelDao;
    private BrandModelButtonDao brandModelButtonDao;
    private UserMachineDao userMachineDao;
    private UserMachineButtonDao userMachineButtonDao;
    private UserLoginDao userLoginDao;
    private BoxLoginDao boxLoginDao;
    private SceneActionDao sceneActionDao;

    private Map<String,String> phoneMap = new HashMap<String, String>();

    private JackMd5 md5 = null;

    private UserServer(){
        setPort(Constants.CONNECTION_MOBILE_TCP_PORT);
        setTlvServerListener(this);
        md5 = new JackMd5();
    }

    public static UserServer getInstance(){
        if(userServer == null){
            userServer = new UserServer();
        }
        return userServer;
    }

    public Context getContext() {
        return context;
    }

    public void setContext(Context context) {
        this.context = context;
        //初始化数据库工具dao
        initModelDao();
    }

    /**
     * 初始化数据工具dao
     */
    private void initModelDao(){
        boxModelDao = new BoxModelDao(context);
        boxPhoneDao = new BoxPhoneDao(context);
        userModelDao = new UserModelDao(context);
        roomModelDao = new RoomModelDao(context);
        deviceModelDao = new DeviceModelDao(context);
        deviceModelHistoryDao = new DeviceModelHistoryDao(context);
        deviceDayPowerConsumptionDao = new DeviceDayPowerConsumptionDao(context);
        deviceMonthPowerConsumptionDao = new DeviceMonthPowerConsumptionDao(context);
        systemValueModelDao = new SystemValueModelDao(context);
        sceneModelDao = new SceneModelDao(context);
        conditionSensorModelDao = new ConditionSensorModelDao(context);
        conditionStatusModelDao = new ConditionStatusModelDao(context);
        conditionTimeModelDao = new ConditionTimeModelDao(context);
        actionModelDao = new ActionModelDao(context);
        actionInfraredModelDao = new ActionInfraredModelDao(context);
        machineTypeDao = new MachineTypeDao(context);
        brandDao = new BrandDao(context);
        buttonDao = new ButtonDao(context);
        brandModelDao = new BrandModelDao(context);
        brandModelButtonDao = new BrandModelButtonDao(context);
        userMachineDao = new UserMachineDao(context);
        userMachineButtonDao = new UserMachineButtonDao(context);
        userLoginDao = new UserLoginDao(context);
        boxLoginDao = new BoxLoginDao(context);
    }

    /**
     * type = 1 ,网关绑定用户消息
     *只允许手机直连机顶盒 或者 直连服务器
     * 直连机顶盒，返回消息，原路返回
     */
    public void doBindBoxUserInfo(String clientId, JSONObject jsonObject){
        BoxModel currentBox = boxModelDao.getCurrentBox();
        String currentBoxCpuId = jsonObject.getString("currentBoxCpuId");

        if(!currentBoxCpuId.equals(currentBox.getBoxCpuId())){
            UserLogoutReply ulr = new UserLogoutReply();
            ulr.setCurrentBoxCpuId(currentBox.getBoxCpuId());
            ulr.setError(Constants.BOX_STATUS_LOGIN_EXP);
            ulr.setMsg("登录参数错误!");
            sendMessage(JSON.toJSONString(ulr), clientId);
            return;
        }

        String userName = jsonObject.getString("userName");
        String password = jsonObject.getString("password");
        final String phoneUid = jsonObject.getString("phoneUid");
        final String phoneName = jsonObject.getString("phoneName");
        String phoneType = jsonObject.getString("phoneType");

        if(StringUtil.isNullOrEmpty(userName, password, phoneUid, phoneName, phoneType)){
            UserLogoutReply ulr = new UserLogoutReply();
            ulr.setCurrentBoxCpuId(currentBox.getBoxCpuId());
            ulr.setError(Constants.BOX_STATUS_LOGIN_EXP);
            ulr.setMsg("登录参数错误!");
            sendMessage(JSON.toJSONString(ulr), clientId);
            return;
        }

        //判断手机终端是否被设置拒绝连接
        BoxPhone boxPhone = boxPhoneDao.getWithPhoneUid(currentBox.getBoxCpuId(), phoneUid);
        if(boxPhone != null){
            if("true".equals(boxPhone.getRefuseFlag())){
                UserLogoutReply ulr = new UserLogoutReply();
                ulr.setCurrentBoxCpuId(currentBox.getBoxCpuId());
                ulr.setError(Constants.BOX_STATUS_UNLOGIN_REFUSE);
                ulr.setMsg("该终端被设置拒绝连接");
                refuseClient(clientId,JSON.toJSONString(ulr));
                return;
            }
        }

        //判断网关是否被用户绑定
        UserModel um = userModelDao.getUserFirst();
        if(um == null){
            //不存在，第一次绑定,存储用户信息
            um = new UserModel();
            um.setUserName(userName);
            um.setNickName(userName);
            um.setPassword(md5.enCription(jsonObject.getString("password")));
            um.setPhone(jsonObject.getString("phone"));
            um.setEmail(jsonObject.getString("email"));
            um.setIdCard(jsonObject.getString("idCard"));
            um.setIp(getClientIp(clientId));
            userModelDao.add(um);

            //更新BOX绑定信息
            boxModelDao.bindUnbindBoxWithUserId(um.getUserName());

            //广播用户信息桌面显示
            userInfoUpdate();

            //更新房间信息
            roomModelDao.updateAllUnbindRoomUserInfo(um.getUserName());

            //存储手机用户
            if(boxPhone == null){
                boxPhone = new BoxPhone();
                boxPhone.setBoxCpuId(currentBoxCpuId);
                boxPhone.setPhoneUid(phoneUid);
            }
            boxPhone.setUserName(userName);
            boxPhone.setPhoneName(phoneName);
            boxPhone.setPhoneType(phoneType);
            boxPhone.setRightful("true");
            boxPhone.setIsConnected("true");
            boxPhoneDao.add(boxPhone);

            //存储用户登录信息
            try {
                UserLogin userLogin ;
                userLogin= userLoginDao.getUserLoginByPhoneUid(phoneUid);
                if (userLogin==null){
                    userLogin = new UserLogin();
                }
                userLogin.setClientId(clientId);
                userLogin.setPhoneUid(phoneUid);
                userLoginDao.add(userLogin);
            } catch (Exception e) {
                userLoginDao.delBy("clientId",clientId);
                UserLogin userLogin = new UserLogin();
                userLogin.setClientId(clientId);
                userLogin.setPhoneUid(phoneUid);
                userLoginDao.add(userLogin);
                e.printStackTrace();
            }

            //通知launcher手机连接上来了
            phoneIn(phoneUid, phoneName);
            //通知桌面机顶盒绑定成功(第一次)
            phoneBind(phoneUid, phoneName);

            //让机顶盒向服务器发起验证
            RemoteClient.getInstance().remoteLogin();

            //反馈手机数据
            UserInfoReply uir = new UserInfoReply();
            uir.setCurrentBoxCpuId(currentBox.getBoxCpuId());
            ////设置用户信息
            uir.setUserInfo(um);
            List<BoxModel> boxList = boxModelDao.getBoxList();
            ////设置BOX信息
            uir.setBoxList(boxList);
            ////设置房间信息
            uir.setRoomList(roomModelDao.getUserRoomList(um.getUserName()));
            ////设置系统常量
            uir.setSystemValueList(systemValueModelDao.getList());
            ////设置情景信息
            uir.setSceneList(sceneModelDao.getList());
            ////设置设备信息
            List<DeviceModel> deviceList = new ArrayList<DeviceModel>();
            for(BoxModel bm : boxList){
                deviceList.addAll(deviceModelDao.getDeviceListByBoxCpuId(bm.getBoxCpuId()));
            }
            uir.setDeviceList(deviceList);
            ////设置家电信息
            uir.setUserMachineList(userMachineDao.getListDetail(userName));

            Log.i("UserServer", JSON.toJSONString(uir));
            sendMessage(JSON.toJSONString(uir),clientId);
        }else{
            //验证密码
            if(!um.getPassword().equals(md5.enCription(password))){

                UserLogoutReply ulr = new UserLogoutReply();
                ulr.setCurrentBoxCpuId(currentBox.getBoxCpuId());
                ulr.setMsg("密码错误!");
                ulr.setError(Constants.BOX_STATUS_LOGIN_EXP);
                sendMessage(JSON.toJSONString(ulr),clientId);
                return;
            }

            //更新登录IP
            um.setIp(getClientIp(clientId));
            userModelDao.add(um);

            //广播用户信息
            userInfoUpdate();

            //存储手机用户
            if(boxPhone == null){
                boxPhone = new BoxPhone();
                boxPhone.setBoxCpuId(currentBoxCpuId);
                boxPhone.setPhoneUid(phoneUid);
            }
            boxPhone.setUserName(userName);
            boxPhone.setPhoneName(phoneName);
            boxPhone.setPhoneType(phoneType);
            boxPhone.setRightful("true");
            boxPhone.setIsConnected("true");
            boxPhoneDao.add(boxPhone);

            //存储用户登录信息
            try {
                UserLogin userLogin ;
                userLogin= userLoginDao.getUserLoginByPhoneUid(phoneUid);
                if (userLogin==null){
                    userLogin = new UserLogin();
                }
                userLogin.setClientId(clientId);
                userLogin.setPhoneUid(phoneUid);
                userLoginDao.add(userLogin);
            } catch (Exception e) {
                userLoginDao.delBy("clientId",clientId);
                UserLogin userLogin = new UserLogin();
                userLogin.setClientId(clientId);
                userLogin.setPhoneUid(phoneUid);
                userLoginDao.add(userLogin);
                e.printStackTrace();
            }

            //通知launcher手机连接上来了
            phoneIn(phoneUid, phoneName);

            //让机顶盒向服务器发起验证
            RemoteClient.getInstance().remoteLogin();

            //发送用户数据
            UserInfoReply uir = new UserInfoReply();
            uir.setCurrentBoxCpuId(boxModelDao.getCurrentBox().getBoxCpuId());
            //设置用户信息
            uir.setUserInfo(um);
            List<BoxModel> boxList = boxModelDao.getBoxList();
            //设置BOX信息
            uir.setBoxList(boxList);
            //设置房间信息
            List<RoomModel> roomList = roomModelDao.getUserRoomList(um.getUserName());
            uir.setRoomList(roomList);
            //设置设备列表信息
            List<DeviceModel> deviceList = new ArrayList<DeviceModel>();
            for(BoxModel bm : boxList){
                deviceList.addAll(deviceModelDao.getDeviceListByBoxCpuId(bm.getBoxCpuId()));
            }
            uir.setDeviceList(deviceList);
            //设置系统常量
            uir.setSystemValueList(systemValueModelDao.getList());
            //设置情景信息
            uir.setSceneList(sceneModelDao.getList());
            ////设置家电信息
            uir.setUserMachineList(userMachineDao.getListDetail(userName));


            Log.i("UserServer", JSON.toJSONString(uir));
            sendMessage(JSON.toJSONString(uir),clientId);
        }
    }

    //type =2.盲添设备消息
    public void doMindAddDevice(JSONObject jsonObject){
        BoxModel currentBox = boxModelDao.getCurrentBox();
        String boxCpuId = jsonObject.getString("boxCpuId");
        if(StringUtil.isNullOrEmpty(boxCpuId)){
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }
        BoxModel boxModel = boxModelDao.getBoxByCpuId(boxCpuId);

        if(currentBox.getBoxCpuId().equals(boxCpuId)){
            AddCmd.getInstance().blindAdd();
        }
            //添加时间戳
            boxModel.setLastHandelTime(DateUtil.getMsDate());
            //更新操作时间
            boxModelDao.add(boxModel);

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }

    }

    //type =3.打开设备
    public void doOpenDevice(String clientId,JSONObject jsonObject){

        BoxModel currentBox = boxModelDao.getCurrentBox();
        String boxCpuId = jsonObject.getString("boxCpuId");

        if(currentBox.getBoxCpuId().equals(boxCpuId)){
            String deviceId = jsonObject.getString("deviceId");
            String deviceNumber = jsonObject.getString("deviceNumber");
            String way = jsonObject.getString("way");
            String deviceStatus = jsonObject.getString("deviceStatus");
            if(way == null){
                way = "01";
            }
          DeviceModel deviceModel=  deviceModelDao.getByCpuIdDeviceIdDeviceNumber(boxCpuId, deviceId, deviceNumber, way);
            if(deviceModel!=null){
                deviceModel.setDeviceStatus(deviceStatus);
                deviceModelDao.add(deviceModel);
            }
            Log.i(getClass().getName(), "收到开启消息:" + " 主机:" + boxCpuId + " 设备类型:" + deviceId + " 设备编号:" + deviceNumber + " 设备路数:" + way + "路");
            if (!StringUtil.isNullOrEmpty(deviceId,deviceNumber)) {
                ControlDeviceCmd.getInstance().openDeviceTackClientId(clientId,boxCpuId, deviceId, deviceNumber, way);
            }

        }


        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());

        }
    }

    //type = 4 关闭设备消息
    public void doCloseDevice(String clientId,JSONObject jsonObject){

        BoxModel currentBox = boxModelDao.getCurrentBox();
        String boxCpuId = jsonObject.getString("boxCpuId");

        if(currentBox.getBoxCpuId().equals(boxCpuId)){
            String deviceId = jsonObject.getString("deviceId");
            String deviceNumber = jsonObject.getString("deviceNumber");
            String way = jsonObject.getString("way");
            String deviceStatus = jsonObject.getString("deviceStatus");
            if(way == null){
                way = "00";
            }
            DeviceModel deviceModel=  deviceModelDao.getByCpuIdDeviceIdDeviceNumber(boxCpuId, deviceId, deviceNumber, way);
            if(deviceModel!=null){
                deviceModel.setDeviceStatus(deviceStatus);
                deviceModelDao.add(deviceModel);
            }
            Log.i(getClass().getName(),"收到关闭消息:" + " 主机:" + boxCpuId + " 设备类型:" + deviceId + " 设备编号:" + deviceNumber);
            if (!StringUtil.isNullOrEmpty(deviceId,deviceNumber)) {
                ControlDeviceCmd.getInstance().closeDeviceTackClientId(clientId,boxCpuId, deviceId, deviceNumber, way);
            }
        }
        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }
    }

    //type = 5 调度设备调度(调光灯，窗帘)
    public void doDemingDevice(String clientId,JSONObject jsonObject){

        BoxModel currentBox = boxModelDao.getCurrentBox();
        String boxCpuId = jsonObject.getString("boxCpuId");

        if(currentBox.getBoxCpuId().equals(boxCpuId)){
            String deviceId = jsonObject.getString("deviceId");
            String deviceNumber = jsonObject.getString("deviceNumber");
            String deviceStatus = jsonObject.getString("deviceStatus");
            String way = jsonObject.getString("way");
            if(way == null){
                way = "00";
            }
            if (!StringUtil.isNullOrEmpty(deviceId,deviceNumber)) {
                ControlDeviceCmd.getInstance().setDimming(boxCpuId, deviceId, deviceNumber, deviceStatus, way);
            }
        }

        //发送所有当前手机
        sendAllUsersMessage(jsonObject.toJSONString());

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }
    }

    /**
     * type = 6 查询设备信息
     * 动作转发到每个主机，每个主机只查询自己的设备，再由各自反馈结果
     * 每个主机从底层获取结果后，更新自己信息，转发给其他主机和服务器，不再经过此方法
     */
    public void doQueryDevice(String clientId,JSONObject jsonObject){

        BoxModel currentBox = boxModelDao.getCurrentBox();
        JSONArray list = jsonObject.getJSONArray("deviceList");

        //不指定查询,只查询本机顶盒设备
        if(list == null || list.size() < 1){
            List<DeviceModel> deviceList = deviceModelDao.getDeviceListByBoxCpuId(jsonObject.getString("currentBoxCpuId"));
            if(deviceList == null || deviceList.size() < 1){
                return;
            }else{
                for(DeviceModel dm : deviceList){
                    QueryCmd.getInstance().query(dm.getBoxCpuId(), dm.getDeviceId(), dm.getDeviceNumber(), dm.getWay());
                }
            }
        }else{ //指定设备查询
            JSONObject deviceObj = null;
            for(int i = 0 ; i < list.size() ; i++){
                deviceObj = list.getJSONObject(i);
                if(currentBox.getBoxCpuId().equals(deviceObj.getString("boxCpuId"))){
                    QueryCmd.getInstance().query(deviceObj.getString("boxCpuId"), deviceObj.getString("deviceId"), deviceObj.getString("deviceNumber"), deviceObj.getString("way"));
                }
            }
        }

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }

        //发送所有当前手机
        UserServer.getInstance().sendAllUsersMessage(jsonObject.toJSONString());
    }

    //type = 7 设备绑定房间/添加房间
    public void doDeviceBindRoom(String clientId, JSONObject jsonObject){
        BoxModel currentBox = boxModelDao.getCurrentBox();
        JSONArray jsonArray = jsonObject.getJSONArray("list");
        RoomModel rm;
        DeviceModel dm;

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject devicesRoom = jsonArray.getJSONObject(i);
            JSONObject roomJsonObject = devicesRoom.getJSONObject("room");
            rm = new RoomModel();
            if(roomJsonObject!=null){
                //创建房间
                rm = roomModelDao.getByName(roomJsonObject.getString("roomName"));
                if(rm == null){
                    rm = new RoomModel();
                    rm.setUserName(currentBox.getUserName());
                    rm.setRoomName(roomJsonObject.getString("roomName"));
                    roomModelDao.add(rm);
                    rm = roomModelDao.getByName(rm.getRoomName());
                }
            }



            //更新设备信息
            if(devicesRoom.getString("boxCpuId") != null
                    && devicesRoom.getString("deviceId") != null
                    && devicesRoom.getString("deviceNumber") != null){
                dm = deviceModelDao.getByCpuIdDeviceIdDeviceNumber(devicesRoom.getString("boxCpuId"),devicesRoom.getString("deviceId"), devicesRoom.getString("deviceNumber"),devicesRoom.getString("way"));
                if(dm != null){
                    if(rm != null){
                        dm.setRoomName(rm.getRoomName());
                    }
                    dm.setDeviceName(devicesRoom.getString("deviceName"));
                    deviceModelDao.add(dm);
                }
            }
        }


//            //添加时间戳
//            if(StringUtil.isNullOrEmpty(jsonObject.getString("lastHandelTime")+"")){
//                boxModel.setLastHandelTime( DateUtil.getDateLong()+"");
//            } else {
//                boxModel.setLastHandelTime(jsonObject.getString("lastHandelTime"));
//            }
//            //更新操作时间
//            boxModelDao.add(boxModel);


        //发送所有当前手机
        sendAllUsersMessageExcept(clientId, jsonObject.toJSONString());

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }
    }

    //type = 8 全开设备
    public void doOpenAllDevices(String clientId,JSONObject jsonObject){

        BoxModel currentBox = boxModelDao.getCurrentBox();
        String boxCpuId = jsonObject.getString("boxCpuId");
        if(StringUtil.isNullOrEmpty(boxCpuId)){
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }

        if(currentBox.getBoxCpuId().equals(boxCpuId)){
            //发送底层指令
            ControlDeviceCmd.getInstance().openAllDevice();

            //变更本地数据
            deviceModelDao.setAllOpen(currentBox.getBoxCpuId());

            //构造同步信息
            DeviceStatusReply dsr = new DeviceStatusReply();
            dsr.setUserName(currentBox.getUserName());
            dsr.setCurrentBoxCpuId(currentBox.getBoxCpuId());
            dsr.setDeviceStatus(deviceModelDao.getOpenCloseAllResult(currentBox.getBoxCpuId()));
            dsr.setHEAD_IS_REPLY("true");

            JSONObject jobj = (JSONObject)JSON.toJSON(dsr);

            //发送所有当前手机
            sendAllUsersMessage(jobj.toJSONString());

            if("false".equals(jobj.getString(MsgConstant.HEAD_IS_REPLY))){
                jobj.put(MsgConstant.HEAD_IS_REPLY,"true");
                //发送服务器
                RemoteClient.getInstance().sendMessage(jobj.toJSONString());
                //发送其他机顶盒
                sendToOtherBoxMessage(jobj.toJSONString());
            }
        }

        //发送所有当前手机
        sendAllUsersMessage(jsonObject.toJSONString());

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }
    }

    //type = 9 全关设备
    public void doCloseAllDevices(String clientId,JSONObject jsonObject){

        BoxModel currentBox = boxModelDao.getCurrentBox();
        String boxCpuId = jsonObject.getString("boxCpuId");
        if(StringUtil.isNullOrEmpty(boxCpuId)){
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }

        if(currentBox.getBoxCpuId().equals(boxCpuId)){
            //发送底层指令
            ControlDeviceCmd.getInstance().closeAllDevice();

            //变更本地数据
            deviceModelDao.setAllClose(currentBox.getBoxCpuId());

            //构造同步信息
            DeviceStatusReply dsr = new DeviceStatusReply();
            dsr.setUserName(currentBox.getUserName());
            dsr.setCurrentBoxCpuId(currentBox.getBoxCpuId());
            dsr.setDeviceStatus(deviceModelDao.getOpenCloseAllResult(currentBox.getBoxCpuId()));
            dsr.setHEAD_IS_REPLY("true");
            JSONObject jobj = (JSONObject)JSON.toJSON(dsr);

            //发送所有当前手机
            sendAllUsersMessage(jobj.toJSONString());

            if("false".equals(jobj.getString(MsgConstant.HEAD_IS_REPLY))){
                jobj.put(MsgConstant.HEAD_IS_REPLY,"true");
                //发送服务器
                RemoteClient.getInstance().sendMessage(jobj.toJSONString());
                //发送其他机顶盒
                sendToOtherBoxMessage(jobj.toJSONString());
            }
        }

        //发送所有当前手机
        sendAllUsersMessage(jsonObject.toJSONString());

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }
    }

    //type = 10 添加一类设备
    public void doAddOneDevice(JSONObject jsonObject){

        BoxModel currentBox = boxModelDao.getCurrentBox();
        String boxCpuId = jsonObject.getString("boxCpuId");
        if(StringUtil.isNullOrEmpty(boxCpuId)){
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }

//        BoxModel boxModel=boxModelDao.getBoxByCpuId(boxCpuId);

        if(currentBox.getBoxCpuId().equals(boxCpuId)){
            AddCmd.getInstance().addOneDevice();
        }

//        if(!("").equals(boxModel) || (boxModel==null)){
//            //添加时间戳
//            if(StringUtil.isNullOrEmpty(jsonObject.getString("lastHandelTime")+"")){
//                boxModel.setLastHandelTime( DateUtil.getDateLong()+"");
//            } else {
//                boxModel.setLastHandelTime(jsonObject.getString("lastHandelTime"));
//            }
//            //更新操作时间
//            boxModelDao.add(boxModel);
//        }

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }
    }

    //type = 13 ,根据主机，类型，编号删除设备
    public void doDeleteDevice(String clientId, JSONObject jsonObject){
        BoxModel currentBox = boxModelDao.getCurrentBox();
        List<DeviceModel> dmList = null;
        JSONArray jsonArray1 = jsonObject.getJSONArray("list");
        JSONObject object = null;
        for (int i = 0; i < jsonArray1.size(); i++) {
            object = jsonArray1.getJSONObject(i);
            if ("1C".equals(object.getString("deviceId"))){
                dmList = deviceModelDao.getByCpuIdDeviceIdDeviceNumberWay(object.getString("boxCpuId"),object.getString("deviceId"), object.getString("deviceNumber"),"01");
            }else {
                dmList = deviceModelDao.getByCpuIdDeviceIdDeviceNumber(object.getString("boxCpuId"),object.getString("deviceId"), object.getString("deviceNumber"));
            }
            if(dmList != null){
                for(DeviceModel dm : dmList){
                    if(currentBox.getBoxCpuId().equals(dm.getBoxCpuId())){
                       if("15".equals(dm.getDeviceId()) || "06".equals(dm.getDeviceId())){
                           try {
                               Thread.currentThread().sleep(3000);
                           } catch (InterruptedException e) {
                               e.printStackTrace();
                           }
                           //向底层发送删除指令
                           RestCmd.getInstance().deanRestOneCmd(dm.getBoxCpuId(), dm.getDeviceId(), dm.getDeviceNumber());
                       }else {
                           try {
                               Thread.currentThread().sleep(3000);
                           } catch (InterruptedException e) {
                               e.printStackTrace();
                           }
                           //向底层发送删除指令
                           RestCmd.getInstance().deanRestOneCmd(dm.getBoxCpuId(), dm.getDeviceId(), "00"+dm.getDeviceNumber());//除了id为15和06设备底层删除设备时候指令少1bit需要在deviceNumber前面拼加00
                       }
                    }

                    //本地数据删除
                    if("1C".equals(object.getString("deviceId"))){
                        deviceModelDao.delByDeviceIdNumber(dm.getBoxCpuId(),dm.getDeviceId(),dm.getDeviceNumber());
                    }else {
                        deviceModelDao.del(dm);
                    }


                }
            }
        }


        //发送所有当前手机
        sendAllUsersMessage(jsonObject.toJSONString());

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 14 停止设备
    public void doStopDevice(String clientId,JSONObject jsonObject){

        BoxModel currentBox = boxModelDao.getCurrentBox();
        DeviceModel dm = deviceModelDao.getByCpuIdDeviceIdDeviceNumber(jsonObject.getString("boxCpuId"), jsonObject.getString("deviceId"), jsonObject.getString("deviceNumber"), jsonObject.getString("way"));
        if(dm != null){
            if(currentBox.getBoxCpuId().equals(dm.getBoxCpuId())){
                ControlDeviceCmd.getInstance().stopDevice(dm.getBoxCpuId(), dm.getDeviceId(), dm.getDeviceNumber(), dm.getWay());
            }
        }

        //发送所有当前手机
        sendAllUsersMessage(jsonObject.toJSONString());

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }
    }

    //type=15 设置新主机名
    public void doSetBoxNewName(String clientId,JSONObject jsonObject){

        String boxCpuId = jsonObject.getString("boxCpuId");
        if(StringUtil.isNullOrEmpty(boxCpuId)){
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }

        String newBoxName = jsonObject.getString("newBoxName");
        if(newBoxName == null || "".equals(newBoxName.trim())){
            return;
        }

        BoxModel boxModel15 = boxModelDao.getBoxByCpuId(boxCpuId);
        if(boxModel15 != null){
            boxModel15.setBoxName(newBoxName);
            boxModelDao.add(boxModel15);
        }

//        //添加时间戳
//        if(StringUtil.isNullOrEmpty(jsonObject.getString("lastHandelTime")+"")){
//            boxModel15.setLastHandelTime( DateUtil.getDateLong()+"");
//        } else {
//            boxModel15.setLastHandelTime(jsonObject.getString("lastHandelTime"));
//        }
//
//        boxModelDao.add(boxModel15);
//        Log.v(TAG,"操作时间更新成功------"+jsonObject.getString("lastHandelTime"));

        //发送所有当前手机
        sendAllUsersMessageExcept(clientId, jsonObject.toJSONString());

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }
    }

    //type=16 复位全部设备,兼容指定主机删除
    public void doResetAllDevice(String clientId,JSONObject jsonObject){

        BoxModel currentBox = boxModelDao.getCurrentBox();
        String boxCpuId = jsonObject.getString("boxCpuId");
        if(StringUtil.isNullOrEmpty(boxCpuId)){
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }

        if(boxCpuId == null || "".equals(boxCpuId.trim())){
            return;
        }

        deviceModelDao.deleteByBoxCpuId(boxCpuId);
        if(currentBox.getBoxCpuId().equals(boxCpuId)){
            //发送删除指令
            RestCmd.getInstance().restAllCmd();
        }

        //发送所有当前手机
        sendAllUsersMessage(jsonObject.toJSONString());

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }
    }

    //type=22 设置校验时间
    public void doSetCheckTime(String clientId,JSONObject jsonObject){

        BoxModel currentBox = boxModelDao.getCurrentBox();

        DeviceModel dm22 = deviceModelDao.getByCpuIdDeviceIdDeviceNumber(jsonObject.getString("boxCpuId"), jsonObject.getString("deviceId"), jsonObject.getString("deviceNumber"), jsonObject.getString("way"));

        if(dm22 != null){
            dm22.setCheckTime(Integer.parseInt(jsonObject.getString("checkTime")));
            deviceModelDao.add(dm22);
        }

        if(currentBox.getBoxCpuId().equals(jsonObject.getString("boxCpuId"))){
            QueryCmd.getInstance().setDeviceCheckTime(dm22.getBoxCpuId(), dm22.getDeviceId(), dm22.getDeviceNumber(), dm22.getWay(), dm22.getCheckTime());
        }

        //发送所有当前手机
        sendAllUsersMessage(jsonObject.toJSONString());

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }

    }

    //type=23 设置电量监控消息
    public void doSetDevicePower(String clientId,JSONObject jsonObject){

        JSONArray list23 = jsonObject.getJSONArray("list");
        JSONObject job23;
        DeviceModel dm23;
        for(int i = 0 ; i < list23.size() ; i++){
            job23 = list23.getJSONObject(i);
            dm23 = deviceModelDao.getByCpuIdDeviceIdDeviceNumber(job23.getString("boxCpuId"),job23.getString("deviceId"), job23.getString("deviceNumber"),job23.getString("way"));
            if(dm23 != null){
                dm23.setPower(job23.getString("power"));
                dm23.setMonitorState(job23.getString("monitorState"));
                deviceModelDao.add(dm23);
            }
        }

        //发送所有当前手机
        sendAllUsersMessage(jsonObject.toJSONString());

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }
    }

    /**
     *type = 24 获取监控的设备电量统计消息
     * 手机直接box，box直接返回到手机
     * 手机直连服务器，服务器直接返回到手机
     */
    public void doGetMonitorDevicesTotalPower(String clientId,JSONObject jsonObject){

        BoxModel currentBox = boxModelDao.getCurrentBox();

        DevicePowerConsumptionReply dpcr24 = new DevicePowerConsumptionReply();
        dpcr24.setCurrentBoxCpuId(currentBox.getBoxCpuId());
        dpcr24.setLastDayPowerConsumption(deviceModelHistoryDao.getLastDayPowerConsumptionFromRecord());
        dpcr24.setLastWeekPowerConsumption(deviceModelHistoryDao.getLastWeekPowerConsumptionFromRecord());
        dpcr24.setLastMonthPowerConsumption(deviceModelHistoryDao.getLastMonthPowerConsumptionFromRecord());

        //发送用户数据
        sendMessage(JSON.toJSONString(dpcr24), clientId);
    }

    //type=25 设置设备始终布防状态
    public void doSetDeviceAlarmFlag(String clientId,JSONObject jsonObject){

        JSONArray list = jsonObject.getJSONArray("list");
        if(list == null){
            return;
        }

        JSONObject job = null;
        DeviceModel dm25 = null;
        for(int i = 0 ; i < list.size() ; i++){
            job = list.getJSONObject(i);
            dm25 = deviceModelDao.getByCpuIdDeviceIdDeviceNumber(job.getString("boxCpuId"),job.getString("deviceId"), job.getString("deviceNumber"),job.getString("way"));
            if(dm25 != null){
                dm25.setAlarmFlag(job.getString("alarmFlag"));
                deviceModelDao.add(dm25);
            }
        }

        //发送所有当前手机
        sendAllUsersMessage(jsonObject.toJSONString());

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }
    }

    //type=26 删除房间
    public void doDeleteRoom(String clientId,JSONObject jsonObject){

        String roomName = jsonObject.getString("roomName");
        if(roomName == null || "".equals(roomName.trim())){
            return;
        }

        if(deviceModelDao.getDeviceListByRoomName(roomName).size() < 1){
            //删除房间数据
            roomModelDao.del(roomModelDao.getByName(roomName));
        }

        //发送所有当前手机
        sendAllUsersMessage(jsonObject.toJSONString());

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }
    }

    //type=28 设置系统布防撤防状态
    public void doSetSystemAlarmFlag(String clientId,JSONObject jsonObject){

        String alarmFlag = jsonObject.getString(GatewaytConstant.SYSTEM_KEY_NAME_ALARM_FLAG);
        if(!"true".equals(alarmFlag) && !"false".equals(alarmFlag)){
            return;
        }

        String boxCpuId = null;

        try{
            boxCpuId = jsonObject.getString("boxCpuId");
        }catch (Exception e){
            e.printStackTrace();
        }

        if(StringUtil.isNullOrEmpty(boxCpuId)){
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }
        SystemValueModel svmd = systemValueModelDao.getByName(boxCpuId,GatewaytConstant.SYSTEM_KEY_NAME_ALARM_FLAG);
        svmd.setValue(alarmFlag);
        systemValueModelDao.add(svmd);

        String type=jsonObject.getString("type");
        if(type=="" || type == null){ //网关板上报数据时候没有带type 网关板解析时候门锁反锁时候直接调用type28
            jsonObject.put("type","28");
            jsonObject.put("currentBoxCpuId",boxCpuId);
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }

        //发送所有当前手机
        sendAllUsersMessage(jsonObject.toJSONString());

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());


        }
    }

    //type 30 查询情景数据，结果原路反馈
    public void doGetSceneInfo(String clientId, JSONObject jsonObject){
        SceneInfoReply sceneInfoReply = new SceneInfoReply();
        sceneInfoReply.setSceneList(sceneModelDao.getList());
        sendMessage(JSONObject.toJSONString(sceneInfoReply), clientId);
    }

    //type 31 添加情景数据
    public void doAddSceneInfo(String clientId, JSONObject jsonObject){

        JSONObject dataObj = jsonObject.getJSONObject("data");
        if(dataObj == null){
            return;
        }

        String sceneName = dataObj.getString("sceneName");
        if(StringUtil.isNullOrEmpty(sceneName)){
            return;
        }
        //判断情景模式名称是否重复
        SceneModel sceneModel = sceneModelDao.getSceneModelOnly(sceneName);
        if(sceneModel != null){
            Log.w(getClass().getName(),"情景名:" + sceneName + "已存在");
            return;
        }

        //1.添加情景数据
        sceneModel = new SceneModel();
        sceneModel.setBoxCpuId(jsonObject.getString("currentBoxCpuId"));
        sceneModel.setSceneName(dataObj.getString("sceneName"));
        sceneModel.setSceneType(dataObj.getInteger("triggerType"));
        sceneModel.setOpenFlag((dataObj.getString("openFlag") == null) ? "true" : dataObj.getString("openFlag"));
        sceneModel.setIconName(dataObj.getString("sceneIcon") == null ? "" : dataObj.getString("sceneIcon") );
        sceneModel.setCheckModel(dataObj.getString("chooseAll"));
        sceneModel.setCreateTime(System.currentTimeMillis());
        sceneModelDao.add(sceneModel);

        //2.添加条件
        ////A.添加时间条件
        JSONArray timeConditionList = dataObj.getJSONArray("conditionTimeList");
        if(timeConditionList!= null){
            if(timeConditionList.size() > 1){
                Log.w(getClass().getName(),"时间条件集合数据大于1");
                return;
            }

            if(timeConditionList.size() > 0){
                JSONObject timeConditionObj = timeConditionList.getJSONObject(0);
                ConditionTimeModel conditionTimeModel = new ConditionTimeModel();
                conditionTimeModel.setSceneName(sceneName);
                conditionTimeModel.setConditionType(0);
                switch (timeConditionObj.getInteger("timeType")){
                    case 0://延时
                        conditionTimeModel.setDelayStartTime(System.currentTimeMillis());
                        conditionTimeModel.setDelayDelayTime(timeConditionObj.getLong("delayTimeMills"));
                        conditionTimeModel.setConditionSubType(0);
                        break;
                    case 1://时效
                        conditionTimeModel.setAgingStartTime(timeConditionObj.getLong("agingTimeMillsFrom"));
                        conditionTimeModel.setAgingStopTime(timeConditionObj.getLong("agingTimeMillsTo"));
                        conditionTimeModel.setConditionSubType(1);
                        break;
                    case 2://定时
                        conditionTimeModel.setConditionSubType(2);
                        conditionTimeModel.setDimingModelType(timeConditionObj.getInteger("timingModel"));
                        conditionTimeModel.setHours(timeConditionObj.getInteger("timingHour"));
                        conditionTimeModel.setMinutes(timeConditionObj.getInteger("timingMinute"));
                        conditionTimeModel.setSeconds(timeConditionObj.getInteger("timingSecond"));
                        switch (conditionTimeModel.getDimingModelType()){
                            case 0://每天
                                break;
                            case 1://每周
                                conditionTimeModel.setWeekDays(timeConditionObj.getString("timingList"));
                                break;
                            case 2://每月
                                conditionTimeModel.setMonthDays(timeConditionObj.getString("timingList"));
                                break;
                            default:
                                Log.w(getClass().getName(),"未定义的定时模式");
                                break;
                        }
                        break;
                    default:
                        Log.w(getClass().getName(),"未定义的时间类型");
                        break;
                }
                conditionTimeModelDao.add(conditionTimeModel);
            }
        }

        ////B.添加状态条件
        JSONArray conditionStateList = dataObj.getJSONArray("conditionStateList");
        if(conditionStateList != null){
            Iterator iterator = conditionStateList.iterator();
            JSONObject conditionStateObj = null;
            ConditionStatusModel conditionStatusModel = null;
            while(iterator.hasNext()){
                conditionStatusModel = new ConditionStatusModel();
                conditionStatusModel.setSceneName(sceneName);
                conditionStatusModel.setConditionType(2);
                conditionStateObj = (JSONObject)iterator.next();
                conditionStatusModel.setConditionSubType(conditionStateObj.getInteger("actionType"));
                conditionStatusModel.setBoxCpuId(conditionStateObj.getString("boxCpuId"));
                conditionStatusModel.setDeviceId(conditionStateObj.getString("deviceId"));
                conditionStatusModel.setDeviceNumber(conditionStateObj.getString("deviceNumber"));
                conditionStatusModel.setWay(conditionStateObj.getString("way")== null ? "01" : conditionStateObj.getString("way"));
                conditionStatusModel.setDeviceName(conditionStateObj.getString("deviceName"));
                conditionStatusModel.setDeviceStatus(conditionStateObj.getString("deviceStatus"));
                conditionStatusModel.setIfAnyone(conditionStateObj.getString("ifAnyone"));
                if("0D".equals(conditionStateObj.getString("deviceId"))){
                    if("00".equals(conditionStateObj.getString("deviceStatus"))){
                        conditionStatusModel.setConditionSubType(1);
                    }else if ("01".equals(conditionStateObj.getString("deviceStatus"))){
                        conditionStatusModel.setConditionSubType(0);
                    }
                }else if ("17".equals(conditionStateObj.getString("deviceId"))){
                    if("C4".equals(conditionStateObj.getString("deviceStatus"))){
                        conditionStatusModel.setConditionSubType(1);
                    }else if ("C0".equals(conditionStateObj.getString("deviceStatus"))){
                        conditionStatusModel.setConditionSubType(0);
                    }

                }else if ("0E".equals(conditionStateObj.getString("deviceId"))){
                    if("77".equals(conditionStateObj.getString("deviceStatus"))){
                        conditionStatusModel.setConditionSubType(1);
                    }else if ("00".equals(conditionStateObj.getString("deviceStatus"))){
                        conditionStatusModel.setConditionSubType(1);
                    }else if ("FF".equals(conditionStateObj.getString("deviceStatus"))){
                        conditionStatusModel.setConditionSubType(0);
                    }
                }else {
                    if("00".equals(conditionStateObj.getString("deviceStatus"))){
                        conditionStatusModel.setConditionSubType(1);
                    }else if ("FF".equals(conditionStateObj.getString("deviceStatus"))){
                        conditionStatusModel.setConditionSubType(0);
                    }
                }
                switch (conditionStatusModel.getConditionSubType()){
                    case 2: //调度状态
                        conditionStatusModel.setDimmingValue(conditionStateObj.getString("deviceStatus"));
                        break;
                    default:
                        break;
                }
                conditionStatusModelDao.add(conditionStatusModel);
            }
        }


        ////C.添加传感条件
        JSONArray conditionSensingList = dataObj.getJSONArray("conditionSensingList");
        if(conditionSensingList != null){
            Iterator iterator1 = conditionSensingList.iterator();
            JSONObject conditionSensorObj = null;
            ConditionSensorModel conditionSensorModel = null;
            while(iterator1.hasNext()){
                conditionSensorObj = (JSONObject)iterator1.next();
                conditionSensorModel = new ConditionSensorModel();
                conditionSensorModel.setSceneName(sceneName);
                conditionSensorModel.setConditionType(1);
                conditionSensorModel.setConditionSubType(conditionSensorObj.getInteger("sensingDeviceType"));
                conditionSensorModel.setBoxCpuId(conditionSensorObj.getString("boxCpuId"));
                conditionSensorModel.setDeviceId(conditionSensorObj.getString("deviceId"));
                conditionSensorModel.setDeviceNumber(conditionSensorObj.getString("deviceNumber"));
                conditionSensorModel.setWay(conditionSensorObj.getString("way") == null ? "01" : conditionSensorObj.getString("way"));
                conditionSensorModel.setDeviceName(conditionSensorObj.getString("deviceName"));
                if (conditionSensorObj.getInteger("sensingDeviceType")!=4){//表示非温湿度时候取检测模型
                    conditionSensorModel.setConditionCheckModel(conditionSensorObj.getString("checkModel"));
                }

                switch (conditionSensorModel.getConditionSubType()){
                    case 0: //二氧化碳
                        conditionSensorModel.setCheckCO2Value(conditionSensorObj.getInteger("checkValue"));
                        break;
                    case 1: //空气质量
                        conditionSensorModel.setCheckAirValue(conditionSensorObj.getString("checkValue"));
                        break;
                    case 2: //PM2.5
                        conditionSensorModel.setCheckPM25Value(conditionSensorObj.getInteger("checkValue"));
                        break;
                    case 3: //光照
                        conditionSensorModel.setCheckLightValue(conditionSensorObj.getInteger("checkValue"));
                        break;
                    case 4: //温湿度
                        String[] values = conditionSensorObj.getString("checkValue").split("\\|");
                        String [] checkModel=conditionSensorObj.getString("checkModel").split("\\|");
                        if(!"null".equals(values[0])){
                            conditionSensorModel.setCheckTemperatureValue(Integer.parseInt(values[0]));
                            conditionSensorModel.setConditionCheckModel(checkModel[0]);
                        }else{
                            conditionSensorModel.setCheckTemperatureValue(-1314);
                            conditionSensorModel.setConditionCheckModel("-1");
                        }

                        if("null".equals(values[0])){
                            conditionSensorModel.setCheckHumidityValue(Integer.parseInt(values[1]));
                            conditionSensorModel.setConditionCheckModel(checkModel[1]);
                        }else{
                            conditionSensorModel.setCheckHumidityValue(-1314);
                        }


                        break;
                    case 5: //风雨传感器

                        break;
                    case 6: //报警类设备
                        conditionSensorModel.setCheckAlarmValue(conditionSensorObj.getString("checkValue"));
                        break;
                    default:
                        Log.w(getClass().getName(),"未定义的传感条件类型");
                        break;
                }
                conditionSensorModelDao.add(conditionSensorModel);
            }
        }


        //3.添加动作
        JSONArray actionList = dataObj.getJSONArray("actionList");
        if(actionList != null){
            Iterator iterator2 = actionList.iterator();
            ActionModel actionModel = null;
            SceneActionModel sceneActionModel=null;
            JSONObject actionObj = null;
            while(iterator2.hasNext()){
                actionObj = (JSONObject)iterator2.next();

                actionModel = new ActionModel();
                actionModel.setSceneName(sceneName);
                actionModel.setActionType(actionObj.getInteger("actionType"));
                actionModel.setBoxCpuId(actionObj.getString("boxCpuId"));
                actionModel.setDeviceId(actionObj.getString("deviceId"));
                actionModel.setDeviceNumber(actionObj.getString("deviceNumber"));
                actionModel.setWay(actionObj.getString("way") == null ? "01" : actionObj.getString("way"));
                actionModel.setDeviceName(actionObj.getString("deviceName"));
                actionModel.setDelayActionTime(actionObj.getInteger("delayTime"));
                actionModel.setOrderNumber(Integer.parseInt(actionObj.getString("actionDeviceOrder")));


//                sceneActionModel = new SceneActionModel();
//                sceneActionModel.setSceneName(sceneName);
//                sceneActionModel.setActionType(actionObj.getInteger("actionType"));
//                sceneActionModel.setBoxCpuId(actionObj.getString("boxCpuId"));
//                sceneActionModel.setDeviceId(actionObj.getString("deviceId"));
//                sceneActionModel.setDeviceNumber(actionObj.getString("deviceNumber"));
//                sceneActionModel.setWay(actionObj.getString("way") == null ? "01" : actionObj.getString("way"));
//                sceneActionModel.setDeviceName(actionObj.getString("deviceName"));
//                sceneActionModel.setDelayActionTime(actionObj.getInteger("delayTime"));
//                sceneActionModel.setOrderNumber(Integer.parseInt(actionObj.getString("actionDeviceOrder")));
                switch (actionModel.getActionType()){
                    case 2:
                        String dimmingValue;
                        if (actionObj.getInteger("dimmingValue")==0){
                             dimmingValue="00";
                        }else {
                            dimmingValue="FF";
                        }
                        actionModel.setDimmingValue(dimmingValue);
                        break;
                    default:
                        break;
                }
                actionModelDao.add(actionModel);
            }
        }


        //添加家电动作
        JSONArray actionInfraredList = dataObj.getJSONArray("actionInfraredList");
        if(actionInfraredList != null){
            Iterator iterator3 = actionInfraredList.iterator();
            JSONObject actionInfraredObj = null;
            ActionInfraredModel actionInfraredModel = null;
            SceneActionModel sceneActionModel=null;
            while(iterator3.hasNext()){
                actionInfraredObj = (JSONObject)iterator3.next();

                actionInfraredModel = new ActionInfraredModel();
                actionInfraredModel.setSceneName(sceneName);
                actionInfraredModel.setActionType(actionInfraredObj.getInteger("actionType"));
                actionInfraredModel.setMachineName(actionInfraredObj.getString("machineName"));
                actionInfraredModel.setButtonId(actionInfraredObj.getInteger("buttonId"));
                actionInfraredModel.setButtonName(actionInfraredObj.getString("buttonName"));
                actionInfraredModel.setDelayActionTime(actionInfraredObj.getInteger("delayTime"));
                actionInfraredModel.setOrderNumber(actionInfraredObj.getInteger("actionInfraredOrder"));
                actionInfraredModelDao.add(actionInfraredModel);

//                sceneActionModel = new SceneActionModel();
//                sceneActionModel.setSceneName(sceneName);
//                sceneActionModel.setActionType(actionInfraredObj.getInteger("actionType"));
//                sceneActionModel.setMachineName(actionInfraredObj.getString("machineName"));
//                sceneActionModel.setButtonId(actionInfraredObj.getInteger("buttonId"));
//                sceneActionModel.setButtonName(actionInfraredObj.getString("buttonName"));
//                sceneActionModel.setDelayActionTime(actionInfraredObj.getInteger("delayTime"));
//                sceneActionModel.setOrderNumber(actionInfraredObj.getInteger("actionInfraredOrder"));
//                sceneActionDao.add(sceneActionModel);
            }
        }
            SceneServer.getInstance().loadSceneList();
            SceneServer.getInstance().setSceneOpenFlag(true);

        //发送所有当前手机
        sendAllUsersMessageExcept(clientId, jsonObject.toJSONString());

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 32 删除情景数据
    public void doDelSceneInfo(String clientId, JSONObject jsonObject){

        String sceneName = jsonObject.getString("sceneName");
        if(StringUtil.isNullOrEmpty(sceneName)){
            return;
        }

        //服务中删除
        SceneServer.getInstance().delScene(sceneName);
        //删除存储的数据
        sceneModelDao.delSceneAllData(sceneName);
        //删除动作数据
        actionInfraredModelDao.del(sceneName);
        //重新加载情景
        SceneServer.getInstance().loadSceneList();

        //发送所有当前手机
        sendAllUsersMessageExcept(clientId,jsonObject.toJSONString());

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 33 手动触发情景
    public void doManualOpenScene(String clientId, JSONObject jsonObject){
        String sceneName = jsonObject.getString("sceneName");

        if(StringUtil.isNullOrEmpty(sceneName)){
            return;
        }

        SceneServer.getInstance().checkPasstiveScene(sceneName);

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 34 打开/关闭被动情景
    public void doSetPasstiveScene(String clientId,JSONObject jsonObject){
        String sceneName = jsonObject.getString("sceneName");
        String openFlag = jsonObject.getString("openFlag");
        if(StringUtil.isNullOrEmpty(sceneName,openFlag)){
            return;
        }

        if(!"true".equals(openFlag) && !"false".equals(openFlag)){
            return;
        }

        SceneModel sceneModel = sceneModelDao.getSceneModelOnly(sceneName);
        if(sceneModel == null){
            return;
        }

        sceneModel.setOpenFlag(openFlag);
        sceneModelDao.add(sceneModel);

        SceneServer.getInstance().loadSceneList();

        //发送所有当前手机
        sendAllUsersMessage(jsonObject.toJSONString());

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }

    }

    //type 35 加音量
    public void doAddSounds(String clientId,JSONObject jsonObject){
        String boxCpuId = jsonObject.getString("boxCpuId");
        if(StringUtil.isNullOrEmpty(boxCpuId)){
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }
        if(boxModelDao.getCurrentBox().getBoxCpuId().equals(boxCpuId)){
            VolumeControl.getInstance().addSounds();
        }

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 36 减音量
    public void doDelSounds(String clientId,JSONObject jsonObject){
        String boxCpuId = jsonObject.getString("boxCpuId");
        if(StringUtil.isNullOrEmpty(boxCpuId)){
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }
        if(boxModelDao.getCurrentBox().getBoxCpuId().equals(boxCpuId)){
            VolumeControl.getInstance().delSounds();
        }

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 37 静音
    public void doNoSounds(String clientId,JSONObject jsonObject){
        String boxCpuId = jsonObject.getString("boxCpuId");
        if(StringUtil.isNullOrEmpty(boxCpuId)){
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }
        if(boxModelDao.getCurrentBox().getBoxCpuId().equals(boxCpuId)){
            VolumeControl.getInstance().setNoSounds();
        }

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 38 静音恢复
    public void doNoSoundsReset(String clientId,JSONObject jsonObject){
        String boxCpuId = jsonObject.getString("boxCpuId");
        if(StringUtil.isNullOrEmpty(boxCpuId)){
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }
        if(boxModelDao.getCurrentBox().getBoxCpuId().equals(boxCpuId)){
            VolumeControl.getInstance().setNoSoundsReset();
        }

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 39 控制向上
    public void doMoveUp(String clientId,JSONObject jsonObject){
        String boxCpuId = jsonObject.getString("boxCpuId");
        if(StringUtil.isNullOrEmpty(boxCpuId)){
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }
        if(boxModelDao.getCurrentBox().getBoxCpuId().equals(boxCpuId)){
            MoveControl.getInstance().moveUp();
        }

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 40 控制向下
    public void doMoveDown(String clientId,JSONObject jsonObject){
        String boxCpuId = jsonObject.getString("boxCpuId");
        if(StringUtil.isNullOrEmpty(boxCpuId)){
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }
        if(boxModelDao.getCurrentBox().getBoxCpuId().equals(boxCpuId)){
            MoveControl.getInstance().moveDown();
        }

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 41 控制向左
    public void doMoveLeft(String clientId,JSONObject jsonObject){
        String boxCpuId = jsonObject.getString("boxCpuId");
        if(StringUtil.isNullOrEmpty(boxCpuId)){
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }
        if(boxModelDao.getCurrentBox().getBoxCpuId().equals(boxCpuId)){
            MoveControl.getInstance().moveLeft();
        }

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 42 控制向右
    public void doMoveRight(String clientId,JSONObject jsonObject){
        String boxCpuId = jsonObject.getString("boxCpuId");
        if(StringUtil.isNullOrEmpty(boxCpuId)){
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }
        if(boxModelDao.getCurrentBox().getBoxCpuId().equals(boxCpuId)){
            MoveControl.getInstance().moveRight();
        }

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 43 返回主页
    public void doBackHome(String clientId,JSONObject jsonObject){
        String boxCpuId = jsonObject.getString("boxCpuId");
        if(StringUtil.isNullOrEmpty(boxCpuId)){
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }
        if(boxModelDao.getCurrentBox().getBoxCpuId().equals(boxCpuId)){
            PageControl.getInstance().backHome();
        }

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 44 弹出系统菜单
    public void doPopMenu(String clientId,JSONObject jsonObject){
        String boxCpuId = jsonObject.getString("boxCpuId");
        if(StringUtil.isNullOrEmpty(boxCpuId)){
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }
        if(boxModelDao.getCurrentBox().getBoxCpuId().equals(boxCpuId)){
            PageControl.getInstance().popMenu();
        }

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 45 返回上页
    public void doBackPre(String clientId,JSONObject jsonObject){
        String boxCpuId = jsonObject.getString("boxCpuId");
        if(StringUtil.isNullOrEmpty(boxCpuId)){
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }
        if(boxModelDao.getCurrentBox().getBoxCpuId().equals(boxCpuId)){
            PageControl.getInstance().backPre();
        }

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 46 OK确认按钮
    public void doConfirm(String clientId,JSONObject jsonObject){
        String boxCpuId = jsonObject.getString("boxCpuId");
        if(StringUtil.isNullOrEmpty(boxCpuId)){
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }
        if(boxModelDao.getCurrentBox().getBoxCpuId().equals(boxCpuId)){
            PageControl.getInstance().confirm();
        }

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }
    }

    //type 47 修改用户信息
    public void doUpdateUserInfo(String clientId,JSONObject jsonObject){

        String userName = jsonObject.getString("userName");
        if(StringUtil.isNullOrEmpty(userName)){
            return;
        }

        UserModel userModel = userModelDao.getByName(userName);
        if(userModel == null){
            return;
        }

        boolean updateFlag = false;

        String phone = jsonObject.getString("phone");
        if(phone == null || "".equals(phone.trim())){

        }else{
            userModel.setPhone(phone);
            updateFlag = true;
        }

        String email = jsonObject.getString("email");
        if(email == null || "".equals(email.trim())){

        }else{
            userModel.setEmail(email);
            updateFlag = true;
        }

        String idCard = jsonObject.getString("idCard");
        if(idCard == null || "".equals(idCard.trim())){

        }else{
            userModel.setIdCard(idCard);
            updateFlag = true;
        }

        String logo = jsonObject.getString("logo");
        if(logo == null || "".equals(logo.trim())){

        }else{
            userModel.setLogo(logo);
            updateFlag = true;
        }

        String nickName = jsonObject.getString("nickName");
        if(nickName == null || "".equals(nickName.trim())){

        }else{
            userModel.setNickName(nickName);
            updateFlag = true;
        }

        String password = jsonObject.getString("password");
        if(password == null || "".equals(password.trim())){

        }else{
            userModel.setPassword(md5.enCription(password));
            updateFlag = true;
        }

        if(!updateFlag){
            return;
        }

        userModelDao.add(userModel);
        userInfoUpdate();

        //发送所有当前手机
        sendAllUsersMessage(jsonObject.toJSONString());

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }
    }

    // type = 48    获取家电类型列表,原路反馈
    public void doGetMachineType(String clientId,JSONObject jsonObject){

        String userName = jsonObject.getString("userName");
        if(StringUtil.isNullOrEmpty(userName)){
            return;
        }
        UserModel userModel = userModelDao.getByName(userName);
        if(userModel == null){
            return;
        }

        List<MachineType> machineTypeList = machineTypeDao.getList();
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("type",jsonObject.getIntValue("type"));
        map.put("userName",userModel.getUserName());
        map.put("machineTypeList", machineTypeList);

        String msg = JSON.toJSONString(map);
        //发送用户数据
        sendMessage(msg, clientId);
    }

    // type = 49    //获取品牌列表
    public void doGetBrand(String clientId,JSONObject jsonObject){
        String userName = jsonObject.getString("userName");
        if(StringUtil.isNullOrEmpty(userName)){
            return;
        }

        int machineTypeId = -1;
        if(jsonObject.containsKey("machineTypeId")){
            machineTypeId = jsonObject.getInteger("machineTypeId");
        }

        UserModel userModel = userModelDao.getByName(userName);
        if(userModel == null){
            return;
        }

        List<Brand> brandList = null;
        if(machineTypeId == -1){
            brandList = brandDao.getList();
        }else{
            brandList = brandDao.getList(machineTypeId);
        }

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("type",jsonObject.getInteger("type"));
        map.put("userName",userModel.getUserName());
        map.put("brandList", brandList);

        String msg = JSON.toJSONString(map);
        //发送用户数据
        sendMessage(msg,clientId);
    }

    // type = 50    //获取型号列表,原路返回
    public void doGetBrandModel(String clientId,JSONObject jsonObject){
        String userName = jsonObject.getString("userName");
        if(StringUtil.isNullOrEmpty(userName)){
            return;
        }

        UserModel userModel = userModelDao.getByName(userName);
        if(userModel == null){
            return;
        }

        if(jsonObject.containsKey("machineTypeId") && jsonObject.containsKey("brandId")){
            int machineTypeId = jsonObject.getInteger("machineTypeId");
            int brandId = jsonObject.getInteger("brandId");
            List<BrandModel> brandModelList = brandModelDao.getList(machineTypeId, brandId);
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("type",jsonObject.getIntValue("type"));
            map.put("userName",userModel.getUserName());
            map.put("brandModelList", brandModelList);

            String msg = JSON.toJSONString(map);
            //发送用户数据
            sendMessage(msg, clientId);
        }
    }

    // type = 51    //根据家电类型获取按钮模板列表,原路返回
    public void doGetButtonTemplete(String clientId,JSONObject jsonObject){
        String userName = jsonObject.getString("userName");
        if(StringUtil.isNullOrEmpty(userName)){
            return;
        }

        UserModel userModel = userModelDao.getByName(userName);
        if(userModel == null){
            return;
        }

        if(jsonObject.containsKey("machineTypeId")){
            int machineTypeId = jsonObject.getInteger("machineTypeId");
            List<Button> buttonTempleteList = buttonDao.getButtonTemplete(machineTypeId);
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("type",jsonObject.getIntValue("type"));
            map.put("userName",userModel.getUserName());
            map.put("buttonTempleteList", buttonTempleteList);

            String msg = JSON.toJSONString(map);
            //发送用户数据
            sendMessage(msg, clientId);
        }
    }

    // type = 52    //根据类型品牌，模糊查询型号列表,原路返回
    public void doGetBrandModelLike(String clientId,JSONObject jsonObject){
        String userName = jsonObject.getString("userName");
        if(StringUtil.isNullOrEmpty(userName)){
            return;
        }

        UserModel userModel = userModelDao.getByName(userName);
        if(userModel == null){
            return;
        }

        if(jsonObject.containsKey("machineTypeId") && jsonObject.containsKey("brandId") && jsonObject.containsKey("modelName")){
            int machineTypeId = jsonObject.getInteger("machineTypeId");
            int brandId = jsonObject.getInteger("brandId");
            String modelName = jsonObject.getString("modelName");
            List<BrandModel> brandModelList = brandModelDao.getListLike(machineTypeId, brandId, modelName);
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("type",jsonObject.getIntValue("type"));
            map.put("userName",userModel.getUserName());
            map.put("brandModelList", brandModelList);

            String msg = JSON.toJSONString(map);
            //发送用户数据
            sendMessage(msg, clientId);
        }
    }

    // type = 53    //根据类型，品牌，按钮查询码库匹配列表,原路反馈
    public void doGetButtonInstructionLike(String clientId,JSONObject jsonObject){

        String userName = jsonObject.getString("userName");
        if(StringUtil.isNullOrEmpty(userName)){
            return;
        }

        UserModel userModel = userModelDao.getByName(userName);
        if(userModel == null){
            return;
        }

        int machineTypeId = jsonObject.getInteger("machineTypeId");
        int brandId = jsonObject.getInteger("brandId");
        int buttonId = jsonObject.getInteger("buttonId");

        List<BrandModel> brandModelList = brandModelDao.getList(machineTypeId, brandId);
        List<BrandModelButton> brandModelButtonList = new ArrayList<BrandModelButton>();

        if(machineTypeId == 5){
            BrandModelButton brandModelButton = null;
            Button button = buttonDao.getButton(buttonId);
            for(BrandModel brandModel : brandModelList){

                if(BrandModel.BRAND_MODEL_TYPE_USER.equals(brandModel.getModelType())){
                    brandModelButton = brandModelButtonDao.get(brandModel.getBrandModelId(),buttonId);
                }else{
                    brandModelButton = new BrandModelButton();
                    brandModelButton.setBrandModelId(brandModel.getBrandModelId());
                    brandModelButton.setButtonId(buttonId);
                    String code = null;
                    if("电源".equals(button.getDisCh())){
                        int[] array = new int[]{0,0,8,0,1};
                        Remote_obj remote_obj = new Remote_obj();
                        String[] result = remote_obj.Creat_air_code(Integer.parseInt(brandModel.getModelName()),1,array);
                        code = result[0];
                    }else if("温度+".equals(button.getDisCh())){
                        int[] array = new int[]{0,0,8,0,1};
                        Remote_obj remote_obj = new Remote_obj();
                        String[] result = remote_obj.Creat_air_code(Integer.parseInt(brandModel.getModelName()),4,array);
                        code = result[0];
                    }
                    brandModelButton.setCode(code);
                }

                if(brandModelButton != null){
                    brandModelButtonList.add(brandModelButton);
                }
            }
        }else{
            BrandModelButton brandModelButton = null;
            for(BrandModel brandModel : brandModelList){
                brandModelButton = brandModelButtonDao.get(brandModel.getBrandModelId(),buttonId);
                if(brandModelButton != null){
                    brandModelButtonList.add(brandModelButton);
                }
            }
        }

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("type", jsonObject.getIntValue("type"));
        map.put("userName", userModel.getUserName());
        map.put("brandModelButtonList", brandModelButtonList);

        String msg = JSON.toJSONString(map);
        //发送用户数据
        sendMessage(msg, clientId);
    }

    // type = 54    //根据类型，品牌，型号，获取按钮列表,原路反馈
    public void doGetBrandModelButtonTemplete(String clientId,JSONObject jsonObject){

        String userName = jsonObject.getString("userName");
        if(StringUtil.isNullOrEmpty(userName)){
            return;
        }

        UserModel userModel = userModelDao.getByName(userName);
        if(userModel == null){
            return;
        }

        int brandModelId = jsonObject.getInteger("brandModelId");
        BrandModel brandModel = brandModelDao.get(brandModelId);
        if(brandModel == null){
            return;
        }

        int machineTypeId = brandModel.getMachineTypeId();
        List<BrandModelButton> brandModelButtonList = null;
//        List<Button> buttonTempleteList = buttonDao.getButtonTemplete(machineTypeId);
        if(5 == machineTypeId){
            brandModelButtonList = new ArrayList<BrandModelButton>();
            List<Button> buttonTempleteList = buttonDao.getButtonTemplete(machineTypeId);
            BrandModelButton brandModelButton;
            Remote_obj remote_obj = new Remote_obj();

            for(Button button : buttonTempleteList){
                if("电源开".equals(button.getDisCh())){
                    int[] array = new int[]{0,4,8,0,1};
                    brandModelButton = new BrandModelButton();
                    brandModelButton.setBrandModelId(brandModelId);
                    brandModelButton.setButtonId(button.getButtonId());

                    String[] result = remote_obj.Creat_air_code(Integer.parseInt(brandModel.getModelName()),1,array);
                    brandModelButton.setCode(result[0]);

                    brandModelButtonList.add(brandModelButton);
                }else if("电源关".equals(button.getDisCh())){
                    int[] array = new int[]{1,4,8,0,1};
                    brandModelButton = new BrandModelButton();
                    brandModelButton.setBrandModelId(brandModelId);
                    brandModelButton.setButtonId(button.getButtonId());

                    String[] result = remote_obj.Creat_air_code(Integer.parseInt(brandModel.getModelName()),1,array);
                    brandModelButton.setCode(result[0]);

                    brandModelButtonList.add(brandModelButton);
                }else if("制热21度".equals(button.getDisCh())){
                    int[] array = new int[]{1,3,6,0,1};
                    brandModelButton = new BrandModelButton();
                    brandModelButton.setBrandModelId(brandModelId);
                    brandModelButton.setButtonId(button.getButtonId());

                    String[] result = remote_obj.Creat_air_code(Integer.parseInt(brandModel.getModelName()),4,array);
                    brandModelButton.setCode(result[0]);

                    brandModelButtonList.add(brandModelButton);

                }else if("制热22度".equals(button.getDisCh())){
                    int[] array = new int[]{1,3,7,0,1};
                    brandModelButton = new BrandModelButton();
                    brandModelButton.setBrandModelId(brandModelId);
                    brandModelButton.setButtonId(button.getButtonId());

                    String[] result = remote_obj.Creat_air_code(Integer.parseInt(brandModel.getModelName()),4,array);
                    brandModelButton.setCode(result[0]);

                    brandModelButtonList.add(brandModelButton);
                }else if("制热23度".equals(button.getDisCh())){
                    int[] array = new int[]{1,3,8,0,1};
                    brandModelButton = new BrandModelButton();
                    brandModelButton.setBrandModelId(brandModelId);
                    brandModelButton.setButtonId(button.getButtonId());

                    String[] result = remote_obj.Creat_air_code(Integer.parseInt(brandModel.getModelName()),4,array);
                    brandModelButton.setCode(result[0]);

                    brandModelButtonList.add(brandModelButton);
                }else if("制热24度".equals(button.getDisCh())){
                    int[] array = new int[]{1,3,9,0,1};
                    brandModelButton = new BrandModelButton();
                    brandModelButton.setBrandModelId(brandModelId);
                    brandModelButton.setButtonId(button.getButtonId());

                    String[] result = remote_obj.Creat_air_code(Integer.parseInt(brandModel.getModelName()),4,array);
                    brandModelButton.setCode(result[0]);

                    brandModelButtonList.add(brandModelButton);
                }else if("制热25度".equals(button.getDisCh())){
                    int[] array = new int[]{1,3,10,0,1};
                    brandModelButton = new BrandModelButton();
                    brandModelButton.setBrandModelId(brandModelId);
                    brandModelButton.setButtonId(button.getButtonId());

                    String[] result = remote_obj.Creat_air_code(Integer.parseInt(brandModel.getModelName()),4,array);
                    brandModelButton.setCode(result[0]);

                    brandModelButtonList.add(brandModelButton);
                }else if("制热26度".equals(button.getDisCh())){
                    int[] array = new int[]{1,3,11,3,1};
                    brandModelButton = new BrandModelButton();
                    brandModelButton.setBrandModelId(brandModelId);
                    brandModelButton.setButtonId(button.getButtonId());

                    String[] result = remote_obj.Creat_air_code(Integer.parseInt(brandModel.getModelName()),4,array);
                    brandModelButton.setCode(result[0]);

                    brandModelButtonList.add(brandModelButton);
                }else if("制冷17度".equals(button.getDisCh())){
                    int[] array = new int[]{1,0,0,0,1};
                    brandModelButton = new BrandModelButton();
                    brandModelButton.setBrandModelId(brandModelId);
                    brandModelButton.setButtonId(button.getButtonId());

                    String[] result = remote_obj.Creat_air_code(Integer.parseInt(brandModel.getModelName()),3,array);
                    brandModelButton.setCode(result[0]);

                    brandModelButtonList.add(brandModelButton);
                }else if("制冷18度".equals(button.getDisCh())){
                    int[] array = new int[]{1,0,1,0,1};
                    brandModelButton = new BrandModelButton();
                    brandModelButton.setBrandModelId(brandModelId);
                    brandModelButton.setButtonId(button.getButtonId());

                    String[] result = remote_obj.Creat_air_code(Integer.parseInt(brandModel.getModelName()),3,array);
                    brandModelButton.setCode(result[0]);

                    brandModelButtonList.add(brandModelButton);
                }else if("制冷19度".equals(button.getDisCh())){
                    int[] array = new int[]{1,0,2,0,1};
                    brandModelButton = new BrandModelButton();
                    brandModelButton.setBrandModelId(brandModelId);
                    brandModelButton.setButtonId(button.getButtonId());

                    String[] result = remote_obj.Creat_air_code(Integer.parseInt(brandModel.getModelName()),3,array);
                    brandModelButton.setCode(result[0]);

                    brandModelButtonList.add(brandModelButton);
                }else if("制冷20度".equals(button.getDisCh())){
                    int[] array = new int[]{1,0,3,0,1};
                    brandModelButton = new BrandModelButton();
                    brandModelButton.setBrandModelId(brandModelId);
                    brandModelButton.setButtonId(button.getButtonId());

                    String[] result = remote_obj.Creat_air_code(Integer.parseInt(brandModel.getModelName()),3,array);
                    brandModelButton.setCode(result[0]);

                    brandModelButtonList.add(brandModelButton);
                }else if("制冷21度".equals(button.getDisCh())){
                    int[] array = new int[]{1,0,4,0,1};
                    brandModelButton = new BrandModelButton();
                    brandModelButton.setBrandModelId(brandModelId);
                    brandModelButton.setButtonId(button.getButtonId());

                    String[] result = remote_obj.Creat_air_code(Integer.parseInt(brandModel.getModelName()),3,array);
                    brandModelButton.setCode(result[0]);

                    brandModelButtonList.add(brandModelButton);
                }else if("制冷22度".equals(button.getDisCh())){
                    int[] array = new int[]{1,0,5,0,1};
                    brandModelButton = new BrandModelButton();
                    brandModelButton.setBrandModelId(brandModelId);
                    brandModelButton.setButtonId(button.getButtonId());

                    String[] result = remote_obj.Creat_air_code(Integer.parseInt(brandModel.getModelName()),3,array);
                    brandModelButton.setCode(result[0]);
                    brandModelButtonList.add(brandModelButton);
//                    brandModelButtonList = brandModelButtonDao.getList(brandModelId);
                }
            }

        }else{
            brandModelButtonList = brandModelButtonDao.getList(brandModelId);
        }

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("type", jsonObject.getIntValue("type"));
        map.put("userName", userModel.getUserName());
        map.put("brandModelButtonList", brandModelButtonList);
        map.put("brandModel", brandModel);

        String msg = JSON.toJSONString(map);
        //发送用户数据
        sendMessage(msg, clientId);
    }

    // type = 55    //发送按钮控制指令,只有手机连接服务器的时候才会转发指令到指定机顶盒
    /**
     * +
     *  bindBoxCpuId
     *  bindDeviceId
     *  bindDeviceNumber
     *  bindWay
     *  isStudyType,是否是true/false
     *
     * @param clientId
     * @param jsonObject
     */
    public void doSendControl(String clientId,JSONObject jsonObject){

        try {
            String userName = jsonObject.getString("userName");
            String isStudyType = jsonObject.getString("isStudyType");
            if(StringUtil.isNullOrEmpty(userName,isStudyType)){
                Log.e(getClass().getName(),"缺少参数userName或者isStudyType");
                return;
            }

            String bindBoxCpuId = jsonObject.getString("bindBoxCpuId");
            String bindDeviceId = jsonObject.getString("bindDeviceId");
            String bindDeviceNumber = jsonObject.getString("bindDeviceNumber");
            String bindWay = jsonObject.getString("bindWay");


            UserModel userModel = userModelDao.getByName(userName);
            if(userModel == null){
                return;
            }

            String toBoxCpuId = jsonObject.getString("currentBoxCpuId");
            long controlKey = jsonObject.getLong("controlKey");
            int deviceType = jsonObject.getInteger("machineTypeId");
            String controlDataStr = jsonObject.getString("controlData");

            BoxModel currentBox = boxModelDao.getCurrentBox();
            if(StringUtil.isNullOrEmpty(bindBoxCpuId,bindDeviceId,bindDeviceNumber,bindWay)){
                if(!currentBox.getBoxCpuId().equals(toBoxCpuId)){
                    if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
                        jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
                        //发送服务器
                        RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
                        //发送其他机顶盒
                        sendToOtherBoxMessage(jsonObject.toJSONString());
                    }
                    return;
                }
            }else{
                if(!currentBox.getBoxCpuId().equals(bindBoxCpuId)){
                    if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
                        jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
                        //发送服务器
                        RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
                        //发送其他机顶盒
                        sendToOtherBoxMessage(jsonObject.toJSONString());
                    }
                    return;
                }
            }

            //如果是空调类,在没有指令的时候，手动生成
            if(5 == deviceType && (null == controlDataStr || "".equals(controlDataStr.trim()))){
                JSONObject controlObj = jsonObject.getJSONObject("controlObj");
                if(controlObj == null){
                    Log.w(getClass().getName(),"用户传输信息数据错误!");
                    return;
                }
                String machineName = controlObj.getString("machineName");
                int type = controlObj.getInteger("type");
                String modelName = controlObj.getString("modelName");
                int power = controlObj.getInteger("power");
                int mode = controlObj.getInteger("mode");
                int temperature = controlObj.getInteger("temperature");
                int windSpeed = controlObj.getInteger("windSpeed");
                int windDirection = controlObj.getInteger("windDirection");

                //计算生成指令码
                int[] array = new int[]{ power, mode, temperature, windSpeed , windDirection };
                Remote_obj remote_obj = new Remote_obj();
                String[] result = remote_obj.Creat_air_code(Integer.parseInt(modelName),type,array);
                controlDataStr = result[0];
            }else{
                if(null == controlDataStr || "".equals(controlDataStr.trim())){
                    return;
                }
            }

            byte[] controlData = HexUtil.HexToByteArr(controlDataStr);


            if(!StringUtil.isNullOrEmpty(bindBoxCpuId,bindDeviceId,bindDeviceNumber,bindWay)){
                if(Boolean.parseBoolean(isStudyType)){
                    InfraredControlCmd.getInstance().controlCmd(bindBoxCpuId,bindDeviceId,bindDeviceNumber,bindWay,controlData, controlKey+"");
                }else{
                    int length = controlData.length + 2;
                    String lengthStr;
                    if(length > 255){
                        lengthStr = Integer.toHexString(length);
                    }else{
                        lengthStr = "00" + Integer.toHexString(length);
                    }

                    InfraredControlCmd.getInstance().controlCmd2(bindBoxCpuId,bindDeviceId,bindDeviceNumber,bindWay,controlData, controlKey+"",HexTool.HexToByteArr(lengthStr),(byte)deviceType);
                }
            }else{
                int deviceId = 0x00;

                ControlMessage controlMessage = new ControlMessage();
                controlMessage.setDeviceType((byte)deviceType);
                controlMessage.setDeviceId((byte) deviceId);
                controlMessage.setControlData(controlData);
                controlMessage.setUserName(userModel.getUserName());
                controlMessage.setControlKey(controlKey);
                int length = controlData.length + 2;
                String lengthStr;
                if(length > 255){
                    lengthStr = Integer.toHexString(length);
                }else{
                    lengthStr = "00" + Integer.toHexString(length);
                }
                controlMessage.setLength(HexTool.HexToByteArr(lengthStr));
                InfraredServer.getInstance().send(controlMessage);
            }
        }catch (Exception e){
            Log.e(getClass().getName(),"发送指令错误:"+e.getMessage());
        }
    }

    /**
     * type = 56   发送按钮学习指令
     * +
     *  bindBoxCpuId
     *  bindDeviceId
     *  bindDeviceNumber
     *  bindWay
     * 只有手机连接服务器的时候才会转发指令到指定机顶盒
     * 学习的结果反馈如果是手机直连主机，直接返回到手机
     * 如果是手机直连服务器，结果通过服务器转发到对应手机
     * (实际上无实际意义，可忽略，因为学习时遥控器还是要跟盒子上的发射板交互，
     * 远程是做不到的，如果后期发射板单独出来再做考虑)
     *
     */
    public void doSendStudy(String clientId,JSONObject jsonObject){

        String userName = jsonObject.getString("userName");
        if(StringUtil.isNullOrEmpty(userName)){
            return;
        }

        String bindBoxCpuId = jsonObject.getString("bindBoxCpuId");
        String bindDeviceId = jsonObject.getString("bindDeviceId");
        String bindDeviceNumber = jsonObject.getString("bindDeviceNumber");
        String bindWay = jsonObject.getString("bindWay");

        UserModel userModel = userModelDao.getByName(userName);
        if(userModel == null){
            return;
        }

        BoxModel currentBox = boxModelDao.getCurrentBox();
        String boxCpuId = jsonObject.getString("boxCpuId");
        if(StringUtil.isNullOrEmpty(boxCpuId)){
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }

        if(jsonObject.containsKey("studyKey")){
            long studyKey = jsonObject.getLong("studyKey");

            if(StringUtil.isNullOrEmpty(bindBoxCpuId,bindDeviceId,bindDeviceNumber,bindWay)){
                if(!currentBox.getBoxCpuId().equals(boxCpuId)){
                    return;
                }

                StudyMessage studyMessage = new StudyMessage();
                studyMessage.setButtonId((byte)0x00);
                studyMessage.setStudyKey(studyKey);
                studyMessage.setUserName(userModel.getUserName());
                InfraredServer.getInstance().send(studyMessage);
            }else{
                InfraredStudyCmd.getInstance(context).InfraredControlCmd(bindBoxCpuId,bindDeviceId,bindDeviceNumber,bindWay,studyKey+"");
            }



        }
    }

    // type = 58    //添加家电设备
    public void doAddUserMachine(String clientId,JSONObject jsonObject){

        String userName = jsonObject.getString("userName");

        UserModel userModel = userModelDao.getByName(userName);
        if(userModel == null){
            return;
        }

        String boxCpuId = jsonObject.getString("boxCpuId");
        if(StringUtil.isNullOrEmpty(boxCpuId)){
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }
        int machineTypeId = jsonObject.getInteger("machineTypeId");
        String brandName = jsonObject.getString("brandName");
        String modelName = jsonObject.getString("modelName");
        String roomName = jsonObject.getString("roomName");
        int addType = jsonObject.containsKey("addType") ? jsonObject.getInteger("addType") : 3 ;
        String machineName = jsonObject.getString("machineName");

        String bindBoxCpuId = jsonObject.getString("bindBoxCpuId");
        String bindDeviceId = jsonObject.getString("bindDeviceId");
        String bindDeviceNumber = jsonObject.getString("bindDeviceNumber");
        String bindWay = jsonObject.getString("bindWay");
        String machineStatus = jsonObject.getString("applianceStatus");
        if(machineTypeId == 11){
            modelName = "自定义型号";
            brandName = "自动以品牌";
        }else{
            if(modelName == null || "".equals(modelName.trim())){
                Log.w(getClass().getName(),"型号名不能为空");
                return;
            }
        }


        Brand brand = brandDao.get(brandName);
        if(brand == null){
            if(machineTypeId == 11){
                brand = new Brand();
                brand.setBrandCh(brandName);
                brand.setBrandEn(brandName);
                brand.setNote(brandName);
                brandDao.add(brand);
                brand = brandDao.get(brandName);
            }else{
                Log.w(getClass().getName(),"品牌不存在!");
                return;
            }
        }
        int brandId= brand.getBrandId();

        BrandModel brandModel = brandModelDao.get(machineTypeId,brand.getBrandId(),modelName);
        if(brandModel == null){
            brandModel = new BrandModel();
            brandModel.setMachineTypeId(machineTypeId);
            brandModel.setBrandId(brandId);
            brandModel.setModelName(modelName);
            brandModel.setModelType("user");
            brandModelDao.add(brandModel);
            brandModel = brandModelDao.get(machineTypeId,brand.getBrandId(),modelName);
        }
            int brandModeId= brandModel.getBrandModelId();
        UserMachine userMachine = userMachineDao.get(userModel.getUserName(),machineName);
        if(userMachine == null){
            userMachine = new UserMachine();
            userMachine.setUserName(userModel.getUserName());
            userMachine.setMachineName(machineName);
            userMachine.setRoomName(roomName);
            userMachine.setAddType(addType);
            userMachine.setBrandModelId(brandModeId);
            userMachine.setBoxCpuId(boxCpuId);
            userMachine.setBindBoxCpuId(bindBoxCpuId);
            userMachine.setBindDeviceNumber(bindDeviceNumber);
            userMachine.setBindDeviceId(bindDeviceId);
            userMachine.setBindWay(bindWay);
            userMachine.setMachineTypeId(machineTypeId);
            userMachine.setStatus(machineStatus);
            userMachineDao.add(userMachine);
        }else{
            Log.w(getClass().getName(),"家电名已存在");
        }

        //发送所有当前手机
        sendAllUsersMessageExcept(clientId, jsonObject.toJSONString());

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }
    }

    // type = 59    //删除家电设备
    public void doDelUserMachine(String clientId,JSONObject jsonObject){

        String userName = jsonObject.getString("userName");
        if(StringUtil.isNullOrEmpty(userName)){
            return;
        }

        UserModel userModel = userModelDao.getByName(userName);
        if(userModel == null){
            return;
        }

        if(jsonObject.containsKey("machineName")){
            String machineName = jsonObject.getString("machineName");
            UserMachine userMachine = userMachineDao.get(userModel.getUserName(), machineName);
            if(userMachine != null){

                //删除设备按钮
                List<UserMachineButton> buttonList = userMachineButtonDao.getList(machineName);
                for(UserMachineButton umb :buttonList){
                    userMachineButtonDao.del(umb);
                }
                //删除设备
                userMachineDao.del(userMachine);
            }else{
                Log.w(getClass().getName(),"家电不存在!");
            }

            //发送所有当前手机
            sendAllUsersMessageExcept(clientId,jsonObject.toJSONString());

            if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
                jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
                //发送服务器
                RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
                //发送其他机顶盒
                sendToOtherBoxMessage(jsonObject.toJSONString());
            }
        }
    }

    // type = 60    //添加家电按钮
    public void doAddMachineButton(String clientId,JSONObject jsonObject){

        String userName = jsonObject.getString("userName");
        if(StringUtil.isNullOrEmpty(userName)){
            return;
        }

        UserModel userModel = userModelDao.getByName(userName);
        if(userModel == null){
            return;
        }

        if(jsonObject.containsKey("machineName") && jsonObject.containsKey("buttonId")){

            String machineName = jsonObject.getString("machineName");
            int buttonId = jsonObject.getInteger("buttonId");

            UserMachineButton userMachineButton = userMachineButtonDao.get(machineName,buttonId);
            if(userMachineButton == null){
                userMachineButton = new UserMachineButton();
                userMachineButton.setMachineName(machineName);
                userMachineButton.setButtonId(buttonId);
            }
            userMachineButton.setButtonName(jsonObject.getString("buttonName"));
            userMachineButton.setCode(jsonObject.getString("code"));
            userMachineButton.setStudyFlag(jsonObject.getString("studyFlag"));
            userMachineButtonDao.add(userMachineButton);

            //发送所有当前手机
            sendAllUsersMessageExcept(clientId, jsonObject.toJSONString());

            if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
                jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
                //发送服务器
                RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
                //发送其他机顶盒
                sendToOtherBoxMessage(jsonObject.toJSONString());
            }
        }
    }

    // type = 61 删除家电按钮
    public void doDelMachineButton(String clientId,JSONObject jsonObject){

        String userName = jsonObject.getString("userName");
        if(StringUtil.isNullOrEmpty(userName)){
            return;
        }

        UserModel userModel = userModelDao.getByName(userName);
        if(userModel == null){
            return;
        }

        if(jsonObject.containsKey("machineName") && jsonObject.containsKey("buttonId")){
            String machineName = jsonObject.getString("machineName");
            int buttonId = jsonObject.getInteger("buttonId");

            UserMachineButton userMachineButton = userMachineButtonDao.get(machineName,buttonId);
            if(userMachineButton != null){
                userMachineButtonDao.del(userMachineButton);

                //发送所有当前手机
                sendAllUsersMessage(jsonObject.toJSONString());

                if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
                    jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
                    //发送服务器
                    RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
                    //发送其他机顶盒
                    sendToOtherBoxMessage(jsonObject.toJSONString());
                }
            }else{
                Log.w(getClass().getName(), "该家电按钮不存在!");
            }
        }
    }

    /**
     * type = 63    手机来电
     * 只用于手机直连机顶盒
     */
    public void doPhoneComming(String clientId,JSONObject jsonObject){
        PhoneControl.getInstance().phoneComming();
    }

    /**
     * type = 64     挂电话
     * 只用于手机直连机顶盒
     */
    public void doPhoneClosed(String clientId,JSONObject jsonObject){
        PhoneControl.getInstance().phoneClosed();
    }

    //type = 65 家电状态同步消息
    public void doSynUserMachineStatus(String clientId,JSONObject jsonObject){

        String userName = jsonObject.getString("userName");
        if(StringUtil.isNullOrEmpty(userName)){
            return;
        }

        UserModel userModel = userModelDao.getByName(userName);
        if(userModel == null){
            return;
        }

        if(jsonObject.containsKey("machineName") && jsonObject.containsKey("status")){

            String machineName = jsonObject.getString("machineName");
            String status = jsonObject.getString("status");

            UserMachine userMachine = userMachineDao.get(userName,machineName);
            if(userMachine != null){
                userMachine.setStatus(status);
                userMachineDao.add(userMachine);
            }

            //发送所有当前手机
            sendAllUsersMessage(jsonObject.toJSONString());

            if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
                jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
                //发送服务器
                RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
                //发送其他机顶盒
                sendToOtherBoxMessage(jsonObject.toJSONString());
            }
        }else{
            Log.w(getClass().getName(),"用户传输信息错误");
            return;
        }
    }

    //type = 66 解绑机顶盒
    public void doUnbindBox(String clientId,JSONObject jsonObject){
        String boxCpuId = jsonObject.getString("boxCpuId");
//        if(StringUtil.isNullOrEmpty(boxCpuId)){
//            boxCpuId = jsonObject.getString("currentBoxCpuId");
//        }

        BoxModel currentBox = boxModelDao.getCurrentBox();

        //发送所有当前手机
        sendAllUsersMessage(jsonObject.toJSONString());

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }

        if(currentBox.getBoxCpuId().equals(boxCpuId)){

            //发送删除指令
            RestCmd.getInstance().restAllCmd();

            //删除服务
            SceneServer.getInstance().stop();
            UserServer.getInstance().stop();
            BoxServer.getInstance().stop();
            RemoteClient.getInstance().stop();
            for(BoxClient boxClient : BoxClientManager.getAll()){
                if(boxClient != null){
                    boxClient.stop();
                }
            }

            //删除网关数据
            deviceModelDao.delAll();
            deviceModelHistoryDao.delAll();
            deviceDayPowerConsumptionDao.delAll();
            deviceMonthPowerConsumptionDao.delAll();

            //删除家电数据
            userMachineDao.delAll();
            userMachineButtonDao.delAll();

            //删除情景数据

            sceneModelDao.delAll();
            actionModelDao.delAll();
            actionInfraredModelDao.delAll();
            conditionTimeModelDao.delAll();
            conditionSensorModelDao.delAll();
            conditionStatusModelDao.delAll();

            //删除房间数据
            roomModelDao.delAll();

            //删除系统设置数据
            systemValueModelDao.delAll();

            //删除手机连接
            userLoginDao.delAll();

            //删除box连接
            boxPhoneDao.delAll();
            boxLoginDao.delAll();

            //删除用户数据
            userModelDao.delAll();

            //删除机顶盒信息
            boxModelDao.delAll();

            EventUnbindBox event = new EventUnbindBox();
            event.setRestartFlag(true);
            event.setBoxCpuId(boxCpuId);
            EventBus.getDefault().post(event);

            Tools.restartSystem(context);

            //删除数据库问卷，重启中重新生成
            File file = new File("/data/data/"+context.getPackageName()+"/databases/smartHomeLauncher.db");
            if(file.exists()){
                file.delete();
            }

        }else{

            //删除机顶盒连接
            for(BoxClient boxClient : BoxClientManager.getAll()){
                if(boxClient.getBoxCpuId().equals(boxCpuId)){
                    boxClient.stop();
                }
            }
            BoxLogin boxLogin = boxLoginDao.getBoxLoginByBoxCpuId(boxCpuId);
            if(boxLogin != null){
                refuseClient(boxLogin.getClientId(),"bye-bye");
            }

            //删除网关数据
            deviceModelDao.delBy("boxCpuId", boxCpuId);
            deviceModelHistoryDao.delBy("boxCpuId", boxCpuId);
            deviceDayPowerConsumptionDao.delBy("boxCpuId", boxCpuId);
            deviceMonthPowerConsumptionDao.delBy("boxCpuId", boxCpuId);

            //删除家电数据
            for(UserMachine um : userMachineDao.getAll()){
                if(um.getBoxCpuId().equals(boxCpuId)){
                    userMachineButtonDao.del(um.getMachineName());
                    actionInfraredModelDao.delBy("machineName",um.getMachineName());
                    userMachineDao.del(um);
                }
            }

            //删除情景数据
            sceneModelDao.delBy("boxCpuId", boxCpuId);
            actionModelDao.delBy("boxCpuId", boxCpuId);
            conditionTimeModelDao.delBy("boxCpuId", boxCpuId);
            conditionSensorModelDao.delBy("boxCpuId", boxCpuId);
            conditionStatusModelDao.delBy("boxCpuId", boxCpuId);
            SceneServer.getInstance().loadSceneList();
            //删除系统设置数据
            systemValueModelDao.delBy("boxCpuId",boxCpuId);

            //删除box连接
            boxLoginDao.delBy("boxCpuId",boxCpuId);

            //删除机顶盒信息
            boxModelDao.delBy("boxCpuId",boxCpuId);

            EventUnbindBox event = new EventUnbindBox();
            event.setRestartFlag(false);
            event.setBoxCpuId(boxCpuId);
            EventBus.getDefault().post(event);
        }
    }

    //type = 67 启动机顶盒直播
    public void doStartHDP(String clientId,JSONObject jsonObject){
        String boxCpuId = jsonObject.getString("boxCpuId");
        if(StringUtil.isNullOrEmpty(boxCpuId)){
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }

        BoxModel currentBox = boxModelDao.getCurrentBox();

        if(currentBox.getBoxCpuId().equals(boxCpuId)){
            String channelName = jsonObject.getString("channelName");
            if(StringUtil.isNullOrEmpty(channelName) || !HdpKit.getinstance().getChannelMap().containsValue(channelName)){
                HdpKit.getinstance().startApp(-1);
            }else{
                HdpKit.getinstance().startApp(HdpKit.getinstance().getChannelNum(channelName));
            }
        }else{
            if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
                jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
                //发送服务器
                RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
                //发送其他机顶盒
                sendToOtherBoxMessage(jsonObject.toJSONString());
            }
        }
    }

    //type = 68 加频道
    public void doAddChannel(String clientId,JSONObject jsonObject){
        String boxCpuId = jsonObject.getString("boxCpuId");
        if(StringUtil.isNullOrEmpty(boxCpuId)){
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }

        BoxModel currentBox = boxModelDao.getCurrentBox();

        if(currentBox.getBoxCpuId().equals(boxCpuId)){
            HdpKit.getinstance().addChannel();
        }else{
            if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
                jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
                //发送服务器
                RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
                //发送其他机顶盒
                sendToOtherBoxMessage(jsonObject.toJSONString());
            }
        }
    }

    //type = 69 减频道
    public void doMinusChannel(String clientId,JSONObject jsonObject){
        String boxCpuId = jsonObject.getString("boxCpuId");
        if(StringUtil.isNullOrEmpty(boxCpuId)){
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }

        BoxModel currentBox = boxModelDao.getCurrentBox();

        if(currentBox.getBoxCpuId().equals(boxCpuId)){
            HdpKit.getinstance().minusChannel();
        }else{
            if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
                jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
                //发送服务器
                RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
                //发送其他机顶盒
                sendToOtherBoxMessage(jsonObject.toJSONString());
            }
        }
    }

    //type = 70 根据频道名打开指定频道
    public void doOpenChanel(String clientId,JSONObject jsonObject){
        String boxCpuId = jsonObject.getString("boxCpuId");
        if(StringUtil.isNullOrEmpty(boxCpuId)){
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }

        BoxModel currentBox = boxModelDao.getCurrentBox();

        if(currentBox.getBoxCpuId().equals(boxCpuId)){
            String channelName = jsonObject.getString("channelName");
            if(StringUtil.isNullOrEmpty(channelName)){
                InfoReply infoReply = new InfoReply();
                infoReply.setBoxCpuId(currentBox.getBoxCpuId());
                infoReply.setInfo("请说出频道名");

                sendMessage(JSON.toJSONString(infoReply));
            }else{
                HdpKit.getinstance().changeChannel(HdpKit.getinstance().getChannelNum(channelName));
            }
        }else{
            if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
                jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
                //发送服务器
                RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
                //发送其他机顶盒
                sendToOtherBoxMessage(jsonObject.toJSONString());
            }
        }
    }

    //type = 71 普通情景开关绑定情景
    public void doBindScene(String clientId,JSONObject jsonObject){
        String boxCpuId = jsonObject.getString("boxCpuId");
        if(StringUtil.isNullOrEmpty(boxCpuId)){
            boxCpuId = jsonObject.getString("currentBoxCpuId");
        }

        JSONObject dataObj = jsonObject.getJSONObject("data");
        if(dataObj == null){
            return;
        }

        String sceneName = dataObj.getString("sceneName");
        if(StringUtil.isNullOrEmpty(sceneName)){
            return;
        }

        //1.绑定之前把该情景绑定过此按键的清除绑定的按键
        SceneModel oldSceneModel = sceneModelDao.getSceneModelByDeviceNumberAndSceneKey(dataObj.getString("deviceNumber"),dataObj.getString("sceneBindKey"));
        if (oldSceneModel!=null) {
            oldSceneModel.setDeviceNumber("00");
            oldSceneModel.setSceneBindKey("00");
            sceneModelDao.add(oldSceneModel);
        }
        //2.情景绑定按键过程
        SceneModel sceneModel = sceneModelDao.getSceneModelOnly(sceneName);
        if(sceneModel!=null){
            sceneModel.setSceneBindKey(dataObj.getString("sceneBindKey"));
            sceneModel.setDeviceNumber(dataObj.getString("deviceNumber"));
            sceneModelDao.add(sceneModel);
            jsonObject.put("bindSceneFlag",true);
        }else {

            jsonObject.put("bindSceneFlag",false);
        }

        //发送所有当前手机
        sendAllUsersMessageExcept(clientId, jsonObject.toJSONString());

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }

    }

    //type = 75 普通开关触发
    public void doSceneKeyDown(String clientId,JSONObject jsonObject){
        String currentBoxCpuId = jsonObject.getString("currentBoxCpuId");
        JSONObject  deviceModelData = jsonObject.getJSONObject("list");
        String deviceNumber = deviceModelData.getString("deviceNumber");
        String sceneBindKey = deviceModelData.getString("deviceStatus");//deviceStatus 也就是绑定的按键标识

        SceneModel sceneModel= sceneModelDao.getSceneModelByDeviceNumberAndSceneKey(deviceNumber,sceneBindKey);

        if (sceneModel!=null || "".equals(sceneModel)){
            String sceneName = sceneModel.getSceneName();
            SceneServer.getInstance().checkPasstiveScene(sceneName);//根据情景名
        }

        if("false".equals(jsonObject.getString(MsgConstant.HEAD_IS_REPLY))){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jsonObject.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jsonObject.toJSONString());
        }
    }

    //type = 74 设置当前设备进度值
    public void doSetProcess(String clientId,JSONObject jobj){

        DeviceModel deviceModel = deviceModelDao.getByCpuIdDeviceIdDeviceNumber(jobj.getString("boxCpuId"),jobj.getString("deviceId"),jobj.getString("deviceNumber"),jobj.getString("way"));
        if(deviceModel != null){
            deviceModel.setProcessValue(jobj.getIntValue("processValue"));
            deviceModelDao.add(deviceModel);
        }

        //发送所有当前手机
        sendAllUsersMessageExcept(clientId,jobj.toJSONString());

        if("false".equals(jobj.getString(MsgConstant.HEAD_IS_REPLY))){
            jobj.put(MsgConstant.HEAD_IS_REPLY,"true");
            //发送服务器
            RemoteClient.getInstance().sendMessage(jobj.toJSONString());
            //发送其他机顶盒
            sendToOtherBoxMessage(jobj.toJSONString());
        }
    }



    public void sendAllUsersMessage(String msg){
        List<UserLogin> userLogins = userLoginDao.getAll();
        for(UserLogin userLogin : userLogins){
            sendMessage(msg, userLogin.getClientId());
        }
    }

    public void sendAllUsersMessageExcept(String clientId,String msg){
        List<UserLogin> userLogins = userLoginDao.getAll();
        for(UserLogin userLogin : userLogins){
            if(!userLogin.getClientId().equals(clientId)){
                sendMessage(msg, userLogin.getClientId());
                Log.v(TAG,"--------发送消息到客户端："+userLogin.getClientId());
            }
        }
    }

    private void sendToOtherBoxMessage(String message){
        List<BoxLogin> boxLogins = boxLoginDao.getAll();
        for(BoxLogin boxLogin : boxLogins){
            BoxServer.getInstance().sendMessage(message, boxLogin.getClientId());
        }
    }

    //发送用户信息更新广播
    public void userInfoUpdate(){
        UserModel userModel = userModelDao.getUserFirst();
        if(userModel != null){
            if(userModel.getUserName() != null){
                Intent intent = new Intent();
                intent.setAction(LauncherMessageReceiver.ACTION_USER_UPDATE_INFO);
                intent.putExtra("userName",userModel.getNickName());
                intent.putExtra("userLogo",userModel.getLogo());
                context.sendBroadcast(intent);
            }
        }
    }

    public void phoneIn(String phoneUid,String phoneName){
        if(!phoneMap.containsKey(phoneUid)){

            EventPhoneAction event = new EventPhoneAction();
            event.setPhoneUid(phoneUid);
            event.setPhoneName(phoneName);
            event.setActionType(EventPhoneAction.PHONE_ACTION_TYPE_ADD);
            EventBus.getDefault().post(event);
        }
        phoneMap.put(phoneUid, phoneName);
    }

    public void phoneOut(String phoneUid){

        EventPhoneAction event = new EventPhoneAction();
        event.setPhoneUid(phoneUid);
        event.setActionType(EventPhoneAction.PHONE_ACTION_TYPE_DEL);
        EventBus.getDefault().post(event);

        phoneMap.remove(phoneUid);
    }

    public void phoneBind(String phoneUid,String phoneName){
        EventPhoneAction event = new EventPhoneAction();
        event.setPhoneUid(phoneUid);
        event.setPhoneName(phoneName);
        event.setActionType(EventPhoneAction.PHONE_ACTION_TYPE_BIND);
        EventBus.getDefault().post(event);
    }

    public void onDisConnected(String clientId){
        BoxModel currentBox = boxModelDao.getCurrentBox();

        UserLogin userLogin = userLoginDao.getUserLoginByClientId(clientId);
        if(userLogin != null){
            BoxPhone boxPhone = boxPhoneDao.getWithPhoneUid(currentBox.getBoxCpuId(), userLogin.getPhoneUid());
            if(boxPhone != null){
                boxPhone.setIsConnected("false");
                boxPhone.setRightful("false");
                boxPhoneDao.add(boxPhone);

                phoneOut(userLogin.getPhoneUid());
            }
            userLoginDao.del(userLogin);
        }
    }

    public void preOnMessage(String clientId,String message){
        if (StringUtil.isNullOrEmpty(message)) {
            return;
        }
        JSONObject jsonObject = null;
        try{
            jsonObject = JSON.parseObject(message.toString());
        }catch (Exception e){
           Log.e(getClass().getName(),"不是json消息:" + e.getMessage());
        }
        if (jsonObject == null) {
            return;
        }

        BoxModel currentBox = boxModelDao.getCurrentBox();

        //二次处理消息
        if(!jsonObject.containsKey(MsgConstant.HEAD_MESSAGE_ID)){
            String messageId = currentBox.getBoxCpuId()+"|"+System.currentTimeMillis();
            jsonObject.put(MsgConstant.HEAD_MESSAGE_ID,messageId);
            MessageIdManager.addMsgId(messageId);
        }

        if(!jsonObject.containsKey(MsgConstant.HEAD_IS_REPLY)){
            jsonObject.put(MsgConstant.HEAD_IS_REPLY,"false");
        }

        //判断拒绝连接
        String phoneUid = jsonObject.getString("phoneUid");
        String currentBoxCpuId = jsonObject.getString("currentBoxCpuId");
        String userName = jsonObject.getString("userName");

        //检测基本参数
        if(StringUtil.isNullOrEmpty(currentBoxCpuId,userName)){
            UserLogoutReply ulr = new UserLogoutReply();
            ulr.setCurrentBoxCpuId(currentBox.getBoxCpuId());
            ulr.setMsg("基本参数错误");
            ulr.setError(Constants.BOX_STATUS_LOGIN_EXP);
            refuseClient(clientId,JSON.toJSONString(ulr));
            return;
        }

        //检测currentBoxCpuId
/*        if(!currentBox.getBoxCpuId().equals(currentBoxCpuId)){
            UserLogoutReply ulr = new UserLogoutReply();
            ulr.setCurrentBoxCpuId(currentBox.getBoxCpuId());
            ulr.setMsg("参数中当前顶盒ID错误");
            refuseClient(clientId,JSON.toJSONString(ulr));
            return;
        }*/

        //判断手机终端是否被设置拒绝连接
        if(!StringUtil.isNullOrEmpty(phoneUid)){
            BoxPhone boxPhone = boxPhoneDao.getWithPhoneUid(currentBox.getBoxCpuId(), phoneUid);
            if(boxPhone != null){
                if("true".equals(boxPhone.getRefuseFlag())){
                    UserLogoutReply ulr = new UserLogoutReply();
                    ulr.setCurrentBoxCpuId(currentBox.getBoxCpuId());
                    ulr.setError(Constants.BOX_STATUS_UNLOGIN_REFUSE);
                    ulr.setMsg("该终端被设置拒绝连接");
                    refuseClient(clientId,JSON.toJSONString(ulr));
                    return;
                }
            }
        }

        //主机已被别的用户绑定
        if(!StringUtil.isNullOrEmpty(currentBox.getUserName())){
            if(!currentBox.getUserName().equals(userName)){
                UserLogoutReply ulr = new UserLogoutReply();
                ulr.setError(Constants.BOX_STATUS_ONBIN_BY_ORDER);
                ulr.setMsg("机顶盒已被用户"+currentBox.getUserName()+"绑定");
                ulr.setCurrentBoxCpuId(currentBox.getBoxCpuId());
                refuseClient(clientId,JSON.toJSONString(ulr));
                return;
            }
        }

        //消息类型
        int type = jsonObject.getIntValue("type");

        //除了登录外，其他消息必须要登录后才能发送
        if(type != 1){
            UserLogin userLogin = userLoginDao.getUserLoginByClientId(clientId);
            if(userLogin == null){
                UserLogoutReply ulr = new UserLogoutReply();
                ulr.setMsg("会话过期请重新登录");
                ulr.setError(Constants.BOX_STATUS_UNLOGIN);
                ulr.setCurrentBoxCpuId(currentBox.getBoxCpuId());
//                refuseClient(clientId,JSON.toJSONString(ulr));
//                return;
            }

            UserModel userModel = userModelDao.getByName(userName);
            if(userModel == null){
                UserLogoutReply ulr = new UserLogoutReply();
                ulr.setMsg("请先绑定用户");
                ulr.setError(Constants.BOX_STATUS_UNBIN);
                ulr.setCurrentBoxCpuId(currentBox.getBoxCpuId());
                refuseClient(clientId,JSON.toJSONString(ulr));
                return;
            }
        }


        switch (type) {
            case 1:		// 网关绑定用户信息
                UserServer.getInstance().doBindBoxUserInfo(clientId, jsonObject);
                break;
            case 2:		// 盲添设备
                UserServer.getInstance().doMindAddDevice(jsonObject);
                break;
            case 3:		// 开启设备
                UserServer.getInstance().doOpenDevice(clientId, jsonObject);
                break;
            case 4:		// 关闭设备
                UserServer.getInstance().doCloseDevice(clientId, jsonObject);
                break;
            case 5:		// 调度设备调度(调光灯，窗帘)
                UserServer.getInstance().doDemingDevice(clientId, jsonObject);
                break;
            case 6:		// 查询设备信息
                UserServer.getInstance().doQueryDevice(clientId, jsonObject);
                break;
            case 7:		// 设备绑定房间
                UserServer.getInstance().doDeviceBindRoom(clientId, jsonObject);
                break;
            case 8:		// 设备全开
                UserServer.getInstance().doOpenAllDevices(clientId, jsonObject);
                break;
            case 9:		// 设备全光
                UserServer.getInstance().doCloseAllDevices(clientId, jsonObject);
                break;
            case 10:	// 添加单个设备
                UserServer.getInstance().doAddOneDevice(jsonObject);
                break;
            case 13:	// 根据主机，类型，编号删除设备
                UserServer.getInstance().doDeleteDevice(clientId, jsonObject);
                break;
            case 14:	//停止设备动作
                UserServer.getInstance().doStopDevice(clientId, jsonObject);
                break;
            case 15:	//设置新主机名
                UserServer.getInstance().doSetBoxNewName(clientId, jsonObject);
                break;
            case 16:	//复位全部设备,兼容指定主机删除
                UserServer.getInstance().doResetAllDevice(clientId, jsonObject);
                break;
            case 17:	//获取用户信息
                //已废弃
                break;
            case 18:	//提示消息(机顶盒->手机)
                break;
            case 19:	//强制退出登录消息(单向，机顶盒->手机)
                break;
            case 20:	//获取情景数据
                break;
            case 21:	//获取红外数据
                break;
            case 22:	//设置校准时间(窗帘设备)
                UserServer.getInstance().doSetCheckTime(clientId, jsonObject);
                break;
            case 23:	//设置电量监控消息
                UserServer.getInstance(). doSetDevicePower(clientId, jsonObject);
                break;
            case 24:	//获取监控的设备电量统计消息
                UserServer.getInstance().doGetMonitorDevicesTotalPower(clientId, jsonObject);
                break;
            case 25: //设置设备始终布防状态
                UserServer.getInstance().doSetDeviceAlarmFlag(clientId, jsonObject);
                break;
            case 26: 	//删除房间
                UserServer.getInstance().doDeleteRoom(clientId, jsonObject);
                break;
            case 28:	//设置系统布防状态
                UserServer.getInstance().doSetSystemAlarmFlag(clientId, jsonObject);
                break;
            case 30:	//查询情景数据
                UserServer.getInstance().doGetSceneInfo(clientId, jsonObject);
                break;
            case 31:	//添加情景数据
                UserServer.getInstance().doAddSceneInfo(clientId, jsonObject);
                break;
            case 32:	//删除情景数据
                UserServer.getInstance().doDelSceneInfo(clientId, jsonObject);
                break;
            case 33:	//手动触发情景
                UserServer.getInstance().doManualOpenScene(clientId, jsonObject);
                break;
            case 34:    //打开/关闭 被动情景
                UserServer.getInstance().doSetPasstiveScene(clientId, jsonObject);
                break;
            case 35:    //加音量
                UserServer.getInstance().doAddSounds(clientId, jsonObject);
                break;
            case 36:    //减音量
                UserServer.getInstance().doDelSounds(clientId, jsonObject);
                break;
            case 37:    //静音
                UserServer.getInstance().doNoSounds(clientId, jsonObject);
                break;
            case 38:    //静音恢复
                UserServer.getInstance().doNoSoundsReset(clientId, jsonObject);
                break;
            case 39:    //控制向上
                UserServer.getInstance().doMoveUp(clientId, jsonObject);
                break;
            case 40:    //控制向下
                UserServer.getInstance().doMoveDown(clientId, jsonObject);
                break;
            case 41:    //控制向左
                UserServer.getInstance().doMoveLeft(clientId, jsonObject);
                break;
            case 42:    //控制向右
                UserServer.getInstance().doMoveRight(clientId, jsonObject);
                break;
            case 43:    //返回主页
                UserServer.getInstance().doBackHome(clientId, jsonObject);
                break;
            case 44:    //弹出系统菜单
                UserServer.getInstance().doPopMenu(clientId, jsonObject);
                break;
            case 45:    //返回上页
                UserServer.getInstance().doBackPre(clientId, jsonObject);
                break;
            case 46:    //OK确认
                UserServer.getInstance().doConfirm(clientId, jsonObject);
                break;
            case 47:    //修改用户信息
                UserServer.getInstance().doUpdateUserInfo(clientId, jsonObject);
                break;
            case 48:    //获取家电类型列表
                UserServer.getInstance().doGetMachineType(clientId, jsonObject);
                break;
            case 49:    //获取品牌列表
                UserServer.getInstance().doGetBrand(clientId, jsonObject);
                break;
            case 50:    //获取型号列表
                UserServer.getInstance().doGetBrandModel(clientId, jsonObject);
                break;
            case 51:    //根据家电类型获取按钮模板列表
                UserServer.getInstance().doGetButtonTemplete(clientId, jsonObject);
                break;
            case 52:    //根据类型品牌，模糊查询型号列表
                UserServer.getInstance().doGetBrandModelLike(clientId, jsonObject);
                break;
            case 53:    //根据类型，品牌，按钮查询码库匹配列表
                UserServer.getInstance().doGetButtonInstructionLike(clientId, jsonObject);
                break;
            case 54:    //根据类型，品牌，型号，获取按钮列表
                UserServer.getInstance().doGetBrandModelButtonTemplete(clientId, jsonObject);
                break;
            case 55:    //发送按钮控制指令
                UserServer.getInstance().doSendControl(clientId, jsonObject);
                break;
            case 56:    //发送按钮学习指令
                UserServer.getInstance().doSendStudy(clientId, jsonObject);
                break;
            case 58:    //添加家电设备
                UserServer.getInstance().doAddUserMachine(clientId, jsonObject);
                break;
            case 59:    //删除家电设备
                UserServer.getInstance().doDelUserMachine(clientId, jsonObject);
                break;
            case 60:    //添加家电按钮
                UserServer.getInstance().doAddMachineButton(clientId, jsonObject);
                break;
            case 61:    //删除家电按钮
                UserServer.getInstance().doDelMachineButton(clientId, jsonObject);
                break;
            case 63:    //来电
                UserServer.getInstance().doPhoneComming(clientId, jsonObject);
                break;
            case 64:    //挂电
                UserServer.getInstance().doPhoneClosed(clientId, jsonObject);
                break;
            case 65:    //同步家电状态
                UserServer.getInstance().doSynUserMachineStatus(clientId,jsonObject);
                break;
            case 66:    //解绑机顶盒
                doUnbindBox(clientId,jsonObject);
                break;
            case 67:    //启动机顶盒直播
                doStartHDP(clientId,jsonObject);
                break;
            case 68:    //加频道
                doAddChannel(clientId,jsonObject);
                break;
            case 69:    //减频道
                doMinusChannel(clientId,jsonObject);
                break;
            case 70:    //根据频道名打开指定频道
                doOpenChanel(clientId,jsonObject);
                break;
            case 71:    //按键绑定情景
                doBindScene(clientId,jsonObject);
                break;
            case 74:
                doSetProcess(clientId,jsonObject);
                break;
            case 75:    //按键绑定情景按键触发
                doSceneKeyDown(clientId,jsonObject);
                break;
            default:
               Log.w(getClass().getName(),"没有定义的消息类型:" + type);
                break;
        }
    }

    @Override
    public void onClientConnect(String clientId) {

    }

    @Override
    public void onClientDisconnect(String clientId) {
        onDisConnected(clientId);
    }

    @Override
    public void onClientMessage(String clientId, String message) {
        preOnMessage(clientId,message);
    }

}
